![](/img/trans.png)
[英]Pandas dataframe- How to count the number of distinct rows for a given ID
[英]How to count number of rows of a pandas DataFrame given conditions
我想计算 pandas DataFrame 的行数,其中某些列的列值为 True。
例如在以下示例 DataFrame 中:
import pandas as pd
from pandas import DataFrame
names = {'First_name': ['Jon','Bill','Maria','Emma'], 'Last_name': ['Bobs', 'Vest', 'Gong', 'Hill'],
'Roll': ['Absent', 'Present', 'Present', 'Absent']}
df = DataFrame(names)
keys = ['Jon', 'Maria', 'Gong', 'Hill', 'Present', 'No']
pattern = r"(?i)" + "|".join(keys)
df['bool1'] = df['First_name'].str.contains(pattern)
df['bool2'] = df['Last_name'].str.contains(pattern)
df
output:
First_name Last_name Roll bool1 bool2
0 Jon Bobs Absent True False
1 Bill Vest Present False False
2 Maria Gong Present True True
3 Emma Hill Absent False True
我想获得“bool1”列或“bool2”列的值为真的行的总数。 也就是说,我应该得到等于 3 的最终总和。
我尝试了以下代码,但它单独添加了行。
df.loc[(df['bool1'] == True) | (df['bool2'] == True)].sum()
我也尝试过 if 语句,但它似乎不正确。
if (df['bool1'] == True) and (df['bool2'] == True):
len(df.index)
如果有人可以帮助解决它,我将不胜感激。 先感谢您。
您想要的可能是过滤后的 dataframe 的长度
len(df[(df['bool1'] == True) | (df['bool2'] == True)])
# or
len(df[(df['bool1']) | (df['bool2'])])
您可以尝试any
类似bool
的列
out = df.filter(like='bool').any(axis=1).sum()
print(out)
3
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.