数据集看起来像这样(在熊猫数据框中) 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
添加回答
举报
0/150
提交
取消