我的 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

uj5u.com熱心網友回復:
您當前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]
請注意,您無需將 a 轉換range為 alist即可對其進行迭代。你可以簡單地做
for i in range(2004, 2012):
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/467794.html
