亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

有沒有辦法在 pandas 中對字典進行分組

有沒有辦法在 pandas 中對字典進行分組

尚方寶劍之說 2023-08-22 10:11:13
嘗試按熊貓中的各大洲對國家/地區的小字典進行分組。結果應該是一個以大洲為索引的索引,以及第一列中的國家/地區數量。 ContinentDict  = {'China':'Asia','United States':'North America',     'Japan':'Asia',    'United Kingdom':'Europe',     'Russian Federation':'Europe',     'Canada':'North America',     'Germany':'Europe',      'India':'Asia','France':'Europe',     'South Korea':'Asia',     'Italy':'Europe',      'Spain':'Europe',                    'Iran':'Asia',     'Australia':'Australia',    'Brazil':'South America'}輸出應該是這樣的Index Country    Column1Asia               5United States      2Europe             6...不必按任何順序排序到目前為止的代碼countries_df = pd.DataFrame.from_dict(ContinentDict,orient='index')    #columns=['size', 'sum', 'mean', 'std']    #countries_df = countries_df.rename(columns={0:"sampCol"})    #countries_df[columns[0]]=np.nan    #countries_df[columns[1]]=np.nan    #countries_df[columns[2]]=np.nan    #countries_df[columns[3]]=np.nan    #countries_df=countries_df.set_index('A').groupby(0)    countries_df=countries_df.rename(index={" ":"Countries"})        #countries_df=countries_df.groupby('sampCol')    #countries_df = countries_df.sum()       #countries_df['size']=countries_df.groupby(['sampCol']).sum()        return countries_df
查看完整描述

2 回答

?
婷婷同學_

TA貢獻1844條經驗 獲得超8個贊

pandas.Series.groupby與以下一起使用count:


s = pd.Series(ContinentDict, name="Country")

s.groupby(s).count()

輸出:


Country

Asia             5

Australia        1

Europe           6

North America    2

South America    1

Name: Country, dtype: int64


查看完整回答
反對 回復 2023-08-22
?
動漫人物

TA貢獻1815條經驗 獲得超10個贊

您可以使用


countries_df = pd.DataFrame(continentDict.items(), columns=('country', 'continent'))

countries_df.groupby('continent').count()

               country

continent             

Asia                 5

Australia            1

Europe               6

North America        2

South America        1


查看完整回答
反對 回復 2023-08-22
  • 2 回答
  • 0 關注
  • 144 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號