如何遍历列表以生成URL的元素。

huangapple go评论87阅读模式
英文:

How to iterate through a list for element of URL generation

问题

当我打印URL时,我得到了列表中的所有元素,而不是我希望的单独的月份:

https://api.census.gov/data/2023/cps/basic/['may', 'apr', 'mar', 'feb', 'jan']?get=NAME, HEFAMINC &for=county:*&in=state:12

我仍在学习Python,所以非常感谢任何帮助!

英文:

I am trying to grab data of census.gov - I would like to run a for loop that rotates through a list of months given, per the API syntax guide.

  1. > # API endpoint and parameters - current pop surveys
  2. base_url = 'https://api.census.gov/data'
  3. year = '2023' # Latest year of data
  4. dataset = 'cps/basic/' # Population and Housing estimates dataset
  5. months = ['may', 'apr', 'mar', 'feb', 'jan'],
  6. get_variables = 'NAME, HEFAMINC ' # Variables aka the column headers
  7. state = '12' # Specify the state code for Florida
  8. county = "*"
  9. # List to store individual data frames
  10. data_frames = []
  11. # Construct the API request URL using an f-string and a for loop to cycle months for 2023
  12. for month in months:
  13. url = f'{base_url}/{year}/{dataset}{month}?get={get_variables}&for=county:{county}&in=state:{state}'
  14. print(url)
  15. # Send the API request
  16. response = requests.get(url)
  17. # Check if the request was successful, otherwise print error message
  18. if response.status_code == 200:
  19. # Parse the JSON response
  20. data = response.json()
  21. # Extract the desired information
  22. headers = data[0] # Column headers
  23. values = data[1:] # Data values
  24. # Create a data frame
  25. df = pd.DataFrame(values, columns=headers)
  26. # Append the data frame to the list
  27. data_frames.append(df)
  28. else:
  29. print(f'Request failed with status code: {response.status_code}')
  30. # Analyze the individual data frames further

When I print the URL, I am getting all elements of the list showing up, not the individual month as I had hoped:

https://api.census.gov/data/2023/cps/basic/['may', 'apr', 'mar', 'feb', 'jan']?get=NAME, HEFAMINC &for=county:*&in=state:12.

I am still learning Python, so any help is greatly appreciated!

答案1

得分: 1

这是行尾的逗号:

  1. months = ['may', 'apr', 'mar', 'feb', 'jan'],

它使months成为一个元组,如果打印months,你会看到:

  1. (['may', 'apr', 'mar', 'feb', 'jan'],)

这使得months的第一个且唯一的元素成为一个列表['may', 'apr', 'mar', 'feb', 'jan']

去掉逗号,问题就会解决。

英文:

It's the comma in the end of the line:

  1. months = ['may', 'apr', 'mar', 'feb', 'jan'],

It makes months a tuple, you can see it if you print months:

  1. (['may', 'apr', 'mar', 'feb', 'jan'],)

Which makes the first and only element of months a list ['may', 'apr', 'mar', 'feb', 'jan'].

Get rid of the comma and the problem will be solved.

huangapple
  • 本文由 发表于 2023年7月12日 21:25:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/76671098.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定