Python Pandas:添加布尔列以帮助过滤每条记录的一个True值

时间:2017-03-30 03:35:12

标签: python pandas

如何将pandas数据框布尔列添加到一起以创建具有真值计数的列?

例如,目的是创建'计数'柱:

a       b       c       count
TRUE    FALSE   FALSE   1
TRUE    TRUE    FALSE   2
TRUE    TRUE    TRUE    3

在python中添加布尔值后(例如True + True = 2),尝试:

df.count = df.a + df.b + df.c

哪个没有工作并发出警告:

UserWarning: evaluating in Python space because the '+' operator is not supported by numexpr for the bool dtype, use '|' instead
  unsupported[op_str]))

目的是简化过滤只有一个True值的记录。

1 个答案:

答案 0 :(得分:2)

您可以使用sum函数,.sum(1)将计算每行的真实性:

df['count'] = df[list("abc")].sum(1)
df

enter image description here

相关问题