数据集看起来像这样(在熊猫数据框中)
Month Year Money
0 Jan 2002 615
1 Feb 2002 756
2 Mar 2002 455
3 Apr 2002 645
4 May 2002 669
5 Jun 2002 913
6 Jul 2002 157
7 Aug 2002 217
8 Sep 2002 985
9 Oct 2002 321
10 Nov 2002 847
11 Dec 2002 179
12 Jan 2003 329
13 Feb 2003 717
14 Mar 2003 278
15 Apr 2003 709
16 May 2003 995
所以,我尝试了pivot
data = df.pivot('Month', 'Year', 'Money')
得到这样的结果:
Year 2002 2003 2004 2005
Month
Apr 645 709 178 800
Aug 217 867 515 748
Dec 179 230 121 905
Feb 756 717 879 772
Jan 615 329 896 108
Jul 157 391 429 699
Jun 913 887 422 537
Mar 455 278 934 906
May 669 995 726 324
Nov 847 536 151 195
Oct 321 950 278 173
Sep 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')
我错过了什么?
HUX布斯
相关分类