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

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

idxmax 在 pivot_table 的情況下不起作用 - Pandas

idxmax 在 pivot_table 的情況下不起作用 - Pandas

縹緲止盈 2023-04-18 16:15:34
數據集看起來像這樣(在熊貓數據框中)   Month  Year  Money0    Jan  2002    6151    Feb  2002    7562    Mar  2002    4553    Apr  2002    6454    May  2002    6695    Jun  2002    9136    Jul  2002    1577    Aug  2002    2178    Sep  2002    9859    Oct  2002    32110   Nov  2002    84711   Dec  2002    17912   Jan  2003    32913   Feb  2003    71714   Mar  2003    27815   Apr  2003    70916   May  2003    995所以,我嘗試了pivotdata = df.pivot('Month', 'Year', 'Money')得到這樣的結果:Year   2002  2003  2004  2005Month                        Apr     645   709   178   800Aug     217   867   515   748Dec     179   230   121   905Feb     756   717   879   772Jan     615   329   896   108Jul     157   391   429   699Jun     913   887   422   537Mar     455   278   934   906May     669   995   726   324Nov     847   536   151   195Oct     321   950   278   173Sep     985   459   915   437意圖是在單獨的列中分配最高值的“年份”。所以,我試過了。data['Max'] = data[['2002, 2003, 2004, 2005']].idxmax(axis=1)這以前適用于簡單的數據框。但是在應用 pivot 之后它向我展示了這個:KeyError                                  Traceback (most recent call last)<ipython-input-57-d841277e2032> in <module>()----> 1 data['Max'] = data[['2002, 2003, 2004, 2005']].idxmax(axis=1)      2 data.head()2 frames/usr/local/lib/python3.6/dist-packages/pandas/core/indexing.py in _validate_read_indexer(self, key, indexer, axis, raise_missing)   1638             if missing == len(indexer):   1639                 axis_name = self.obj._get_axis_name(axis)-> 1640                 raise KeyError(f"None of [{key}] are in the [{axis_name}]")   1641    1642             # We (temporarily) allow for some missing keys with .loc, except in同樣的錯誤!KeyError: "None of [Index(['2002, 2003, 2004, 2005'], dtype='object', name='Year')] are in the [columns]"print(data.columns)顯示索引(['Month', 2002, 2003, 2004, 2005], dtype='object', name='Year')我錯過了什么?
查看完整描述

1 回答

?
HUX布斯

TA貢獻1876條經驗 獲得超6個贊

我想你想要:

data['Max'] = data.idxmax(axis=1)

或者如果你想要特定的年份:

data['Max'] = data[[2002,2003,2004,2005]].idxmax(axis=1)

如果你Year是整數,否則:

data['Max'] = data[['2002','2003','2004','2005']].idxmax(axis=1)

而不是使用大字符串進行索引'2002, 2003, 2004, 2005'。

輸出:

Year   2002  2003  2004  2005   Max

Month                              

Apr     645   709   178   800  2005

Aug     217   867   515   748  2003

Dec     179   230   121   905  2005

Feb     756   717   879   772  2004

Jan     615   329   896   108  2004

Jul     157   391   429   699  2005

Jun     913   887   422   537  2002

Mar     455   278   934   906  2004

May     669   995   726   324  2003

Nov     847   536   151   195  2002

Oct     321   950   278   173  2003

Sep     985   459   915   437  2002


查看完整回答
反對 回復 2023-04-18
  • 1 回答
  • 0 關注
  • 197 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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