For 循环不读取列表中的所有值 - 数据框

For loop doesn't read all the value in the list - dataframe

我的 for 循环没有读取 (2004,2012) 范围内的所有值,这很奇怪。当我在我的 for 循环中尝试一个简单的函数时,例如 return a,我确实看到它读取了范围内的所有值。但是,当我使用 pd.read_json 时,它的工作原理就不一样了。我将数据转换为数据框,但我的数据框中只显示了一年。我的 for 循环中是否遗漏了什么?

test = range(2004, 2012)
testlist = list(test)

for i in testlist:
     a = f"https://api.census.gov/data/{i}/cps/basic/jun?get=GTCBSA,PEMNTVTY&for=state:*"
     b = pd.read_json(a) 
     c= pd.DataFrame(b.iloc[1:,]).set_axis(b.iloc[0,], axis="columns", inplace=False)
     c['year'] = i

您目前在循环的每一遍中都覆盖了 c。相反,您需要 concat 新数据到它的末尾:

test = range(2004, 2012)
testlist = list(test)

c = pd.DataFrame()
for i in testlist:
     a = f"https://api.census.gov/data/{i}/cps/basic/jun?get=GTCBSA,PEMNTVTY&for=state:*"
     b = pd.read_json(a) 
     b = pd.DataFrame(b.iloc[1:,]).set_axis(b.iloc[0,], axis="columns", inplace=False)
     b['year'] = i
     c = pd.concat([c, b])

输出:

0      GTCBSA PEMNTVTY state  year
1           0      316     2  2004
2           0       57     2  2004
3           0       57     2  2004
4           0       57     2  2004
5       22900       57     5  2004
...       ...      ...   ...   ...
133679      0      120    56  2011
133680      0       57    56  2011
133681      0       57    56  2011
133682      0       57    56  2011
133683      0       57    56  2011

[1087063 rows x 4 columns]

请注意,您无需将 range 转换为 list 即可对其进行迭代。你可以简单地做

for i in range(2004, 2012):