Skip to main content
 首页 » 编程设计

python之每行字符串出现的总和数

2025年05月04日21mfrbuaa

我一直在尝试为此寻找答案,但找不到 - 我一定是误会了什么。

我只想对每行出现字符串(“True”)的次数求和。所需的输出如下:

d1 = {'score': ['True', 'True', 'False'], 'score2': ['False', 'True', 'True'], 'total': [1, 2, 1]} 
df1 = pd.DataFrame(data=d1) 

请您参考如下方法:

试试这个,

df1['total']= df1.eq('True').sum(axis=1) 

如果 df 是 bool 值,试试这个,

df1['total']= df1.eq(True).sum(axis=1) 

为了更简洁的方式,

df1['total']= df1.sum(axis=1) 

输出:

   score score2  total 
0   True  False      1 
1   True   True      2 
2  False   True      1