我有一个 Pandas DataFrame 如下:
In [28]: df = pd.DataFrame({'A':['CA', 'FO', 'CAP', 'CP'],
'B':['Name1', 'Name2', 'Name3', 'Name4'],
'C':['One', 'Two', 'Other', 'Some']})
In [29]: df
Out[29]:
A B C
0 CA Name1 One
1 FO Name2 Two
2 CAP Name3 Other
3 CP Name4 Some
我正在尝试计算 A 列中具有 'CA'
和 'CP'
值的所有记录,为此我正在执行下一个:
In [30]: len(df.groupby('A').filter(lambda x: x['A'] == 'CA'))
Out[30]: 1
有没有办法在一个句子中获取这两个信息?,因为如果我尝试做这样的事情:
In [32]: len(df.groupby('A').filter(lambda x: x['A'] == 'CA' or
....: x['A'] == 'CP'))
我收到这个错误:
ValueError Traceback (most recent call last)
<ipython-input-32-111c3fde30f2> in <module>()
----> 1 len(df.groupby('A').filter(lambda x: x['A'] == 'CA') or
2 x['A'] == 'CP')
c:\python27\lib\site-packages\pandas\core\generic.pyc in __nonzero__(self)
885 raise ValueError("The truth value of a {0} is ambiguous. "
886 "Use a.empty, a.bool(), a.item(), a.any() or a.all()."
--> 887 .format(self.__class__.__name__))
888
889 __bool__ = __nonzero__
ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
最佳答案
使用isin
并在获取大小之前传递一个列表来过滤 df:
In [4]:
len(df[df['A'].isin(['CA','CP'])])
Out[4]:
2
关于python - 在 python pandas dataframe groupby 上应用两个过滤条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37000231/