【问题标题】:Sum number of occurences of string per row总和每行字符串的出现次数
【发布时间】:2018-11-02 11:02:49
【问题描述】:

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

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

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

【问题讨论】:

标签: python pandas


【解决方案1】:

试试这个,

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

如果 df 是布尔值,试试这个,

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

【讨论】:

  • @SebSilas - 你能从 True 中删除引号吗,我的意思是不要尝试 True,而不是 'True'。
【解决方案2】:

字符串值:eq + sum

df1['total'] = df1[['score', 'score2']].eq('True').sum(1)

print(df1)

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

布尔值:sum

在这种情况下不需要执行布尔测试:

df1['total'] = df1[['score', 'score2']].sum(1)

【讨论】:

  • 嗯,这也给我每行 0。
  • 在这种情况下,它需要不带引号的 True。谢谢!
  • @SebSilas,对于布尔值,您不需要使用eq,请参阅更新。
猜你喜欢
  • 2022-10-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-15
  • 2016-01-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多