我想在下面的DataFrame中按字母数字求和:
In [10]: df
Out[10]:
letter number
0 A 1
1 A 2
2 B 3
3 B 4
4 C 5
5 C 6
[6 rows x 2 columns]
这很容易实现:
In [11]: df.groupby('letter')[['number']].sum()
Out[11]:
number
letter
A 3
B 7
C 11
[3 rows x 1 columns]
但如果我拼错了我的专栏,我会得到NaN
个值:
In [12]: df.groupby('letter')[['numberrrrr']].sum()
Out[12]:
numberrrrr
letter
A NaN
B NaN
C NaN
[3 rows x 1 columns]
这导致我们的团队非常追逐以确定错误的位置。相反,我们想要一个错误陈述,如:
In [13]: df.groupby('letter')['numberrrrr'].sum()
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-13-8ebcdeee8710> in <module>()
----> 1 df.groupby('letter')['numberrrrr'].sum()
/usr/local/Anaconda/lib/python2.7/site-packages/pandas/core/groupby.pyc in __getitem__(self, key)
2475 else:
2476 if key not in self.obj: # pragma: no cover
-> 2477 raise KeyError(str(key))
2478 # kind of a kludge
2479 return SeriesGroupBy(self.obj[key], selection=key,
KeyError: 'numberrrrr'
当请求的列丢失时,是否有任何特殊原因从聚合返回DataFrame不会导致错误?
这是关于pandas 0.13.1。
答案 0 :(得分:3)
这在master / 0.14.0(本周结束)中修复;如果您想尝试
,则rc1为hereIn [7]: df.groupby('letter')[['number']].sum()
Out[7]:
number
letter
A 3
B 7
C 11
In [8]: df.groupby('letter')[['numberrrr']].sum()
KeyError: "Columns not found: 'numberrrr'"
In [9]: pd.__version__
Out[9]: '0.14.0rc1-43-g0dec048'