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

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

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.

> # API endpoint and parameters - current pop surveys
base_url = 'https://api.census.gov/data'
year = '2023'  # Latest year of data
dataset = 'cps/basic/'  # Population and Housing estimates dataset
months = ['may', 'apr', 'mar', 'feb', 'jan'], 
get_variables = 'NAME, HEFAMINC '  # Variables aka the column headers
state = '12'  # Specify the state code for Florida
county = "*"

# List to store individual data frames
data_frames = []

# Construct the API request URL using an f-string and a for loop to cycle months for 2023
for month in months:
    url = f'{base_url}/{year}/{dataset}{month}?get={get_variables}&for=county:{county}&in=state:{state}'
    print(url)

    # Send the API request
    response = requests.get(url)

    # Check if the request was successful, otherwise print error message
    if response.status_code == 200:
        # Parse the JSON response
        data = response.json()

        # Extract the desired information
        headers = data[0]  # Column headers
        values = data[1:]  # Data values

        # Create a data frame
        df = pd.DataFrame(values, columns=headers)

        # Append the data frame to the list
        data_frames.append(df)
    else:
        print(f'Request failed with status code: {response.status_code}')

# 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

这是行尾的逗号:

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

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

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

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

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

英文:

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

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

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

(['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:

确定