python pandas 过滤 true、false 和两者的列

标签 python pandas dataframe filter

我目前正在尝试使用某些 bool 列来过滤 pandas df,以获取 true、false 以及循环中的两种类型。

为了更好的解释,假设我们有以下 df:

df = pd.DataFrame({
'a': [1, 2, 3, 5, 6, 7, 8, 9, 10], 
'b': [True, True, True, False, False, True, False, True, False], 
'c': [True, False, False, False, True, True, True, True, False], 
'd': [35, 59, 12, 2, 19, 24, 33, 5, 11]
})

我现在想做的是循环两个 bool 列,如下所示:

loops = [[True, True], [True, any], [any, True], [any, any]]

for loop in loops:
df[(df['b'] == loop[0]) & (df['c'] == loop[1])]['d'].sum()

不幸的是,使用 any 以及 bool 都不起作用。

有人知道如何存档吗?

谢谢!

最佳答案

使用 any 在这里没有意义,这是一个函数,而不是 pandas 能够理解的通用术语。

为什么不使用 set 来满足您的条件?

T = {True}
F = {False}
ANY = {True, False}
NONE = {}

loops = [[T, T], [T, ANY], [ANY, T], [ANY, ANY]]

for loop in loops:
    x = df[df['b'].isin(loop[0]) & df['c'].isin(loop[1])]['d'].sum()
    print(loop, x)

输出:

[{True}, {True}] 64
[{True}, {False, True}] 135
[{False, True}, {True}] 116
[{False, True}, {False, True}] 200

替代使用函数

如果您创建自定义函数,请确保它们已矢量化。

def istrue(x):
    return x == True  # or just "return x" if you only have booleans

def isfalse(x):
    return x == False # not using "~ x" to make the function generic

def isany(x):
    return x | True

def isnone(x):
    return x & False

loops = [[istrue, istrue], [istrue, isany], [isany, istrue], [isany, isany]]

for loop in loops:
    x = df[loop[0](df['b']) & loop[1](df['c'])]['d'].sum()
    print([x.__name__ for x in loop], x)

输出:

['istrue', 'istrue'] 64
['istrue', 'isany'] 135
['isany', 'istrue'] 116
['isany', 'isany'] 200

关于python pandas 过滤 true、false 和两者的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76785441/

相关文章:

python - Flask-Admin Role Based Access - 根据角色修改访问权限

python - 使用自定义函数后如何存储新的数据框?

python - 使用 C++ 或 Python 将表格 PDF 数据转换为文本(或任何其他可读格式)文件

javascript - 在 django 中显示图像

python - 如何将 PIL ImageDraw 转换为 Image

python - Pandas 迭代中每一行的并行处理

python - pandas 在另一列上的 groupby 之后绘制一列的不同值

Python 和 Pandas 对象赋值

r - 按组以字符格式汇总金额

python - 从 json 转换为 dataframe 再到 sql