我有一個 countrydf 如下,其中 country 列中的每個單元格都包含電影發行國家/地區的串列。
countrydf
id Country release_year
s1 [US] 2020
s2 [South Africa] 2021
s3 NaN 2021
s4 NaN 2021
s5 [India] 2021
我想制作一個新的 df 看起來像這樣:
country_yeardf
Year US UK Japan India
1925 NaN NaN NaN NaN
1926 NaN NaN NaN NaN
1927 NaN NaN NaN NaN
1928 NaN NaN NaN NaN
它有發行年份和每個國家發行的電影數量。我的解決方案是:使用像第二個一樣的空白 df,運行 for 回圈來計算發布的電影數量,然后相對地修改單元格中的值。
countrylist=['Afghanistan', 'Aland Islands', 'Albania', 'Algeria', 'American Samoa', 'Andorra', 'Angola', 'Anguilla', 'Antarctica', ….]
for x in countrylist:
for j in list(range(0,8807)):
if x in countrydf.country[j]:
t=int (countrydf.release_year[j] )
country_yeardf.at[t, x] = country_yeardf.at[t, x] 1
發生錯誤,內容如下:
TypeError Traceback (most recent call last)
<ipython-input-25-225281f8759a> in <module>()
1 for x in countrylist:
2 for j in li:
----> 3 if x in countrydf.country[j]:
4 t=int(countrydf.release_year[j])
5 country_yeardf.at[t, x] = country_yeardf.at[t, x] 1
TypeError: argument of type 'float' is not iterable
我不知道這里哪個是 float 型別,我檢查了 countrydf.country[j] 的型別,它回傳了 int。我正在使用熊貓,我才剛剛開始使用它。任何人都可以解釋錯誤并為我想要創建的 df 提出解決方案嗎?P/s:我的英語不是很好,所以希望你們理解。
uj5u.com熱心網友回復:
這是使用的解決方案 groupby
df = pd.DataFrame([['US', 2015], ['India', 2015], ['US', 2015], ['Russia', 2016]], columns=['country', 'year'])
country year
0 US 2015
1 India 2015
2 US 2015
3 Russia 2016
現在只需按國家和年份分組并拆開輸出:
df.groupby(['year', 'country']).size().unstack()
country India Russia US
year
2015 1.0 NaN 2.0
2016 NaN 1.0 NaN
uj5u.com熱心網友回復:
在沒有回圈的熊貓中實作這一點的一些替代方法。
如果 Country Column 在每行的串列中都有 1 個以上的值,您可以嘗試以下操作:
>>df['Country'].str.join("|").str.get_dummies().groupby(df['release_year']).sum()
India South Africa US
release_year
2020 0 0 1
2021 1 1 0
否則,如果 Country 在串列中的每行只有 1 個值,如示例中所示,您可以使用 crosstab
>>pd.crosstab(df['release_year'],df['Country'].str[0])
Country India South Africa US
release_year
2020 0 0 1
2021 1 1 0
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/392852.html
下一篇:使用函式檢索要放入資料幀的鍵
