python - 如何在 python pandas 中使用带有 bool 的查询函数?

标签 python pandas dataframe

我正在尝试做类似的事情

df.query("'column' == 'a'").count()

但与

df.query("'column' == False").count()

query 与 bool 列一起使用的正确方法是什么?

最佳答案

它只是'column == False'

>>> df = pd.DataFrame([[False, 1], [True, 2], [False, 3]], columns=['column', 'another_column'])                       
>>> df                                                                                                                 
   column  another_column
0   False               1
1    True               2
2   False               3
>>> df.query('column == False')                                                                                        
   column  another_column
0   False               1
2   False               3
>>> df.query('column == False').count()                                                                                
column            2
another_column    2
dtype: int64

就个人而言,我更喜欢 bool 索引(如果适用于您的情况)。

>>> df[~df['column']]                                                                                                  
   column  another_column
0   False               1
2   False               3
>>> df[~df['column']].count()                                                                                          
column            2
another_column    2
dtype: int64

关于python - 如何在 python pandas 中使用带有 bool 的查询函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53786421/

相关文章:

python - 对平方数组求和

python - "WindowsError: exception: access violation..."- ctypes 问题

python - Groupby 与行索引操作?

r - 将相同数据帧的列表熔化到 R 中的一个数据帧

用组内其他列的第一个或最后一个值替换数据帧中的 NA 值

python - 在 pygame 中,重置每个 Sprite 位置的最有效方法是什么?

python - RF : Replace ${SPACE}, ${EMPTY} 和 - 值为 '0'

python - 如何通过析取语句(逻辑 "or")对 pandas DataFrame 进行切片?

python - Matplotlib savefig 截断pyplot表

python - 为什么我的多索引数据框有重复的索引值?