【问题标题】:Count the number of column for each rows of a pandas where a condition holds计算条件成立的熊猫每行的列数
【发布时间】:2020-03-15 23:49:13
【问题描述】:

我有一个 Pandas 数据框如下:

data = pd.DataFrame({'w1':[0,1,0],'w2':[5,8,0],'w3':[0,0,0],'w4' :[5,1,0], 'w5' : [7,1,0],'condition' : [5,1,0]})

我需要有一列,对于每一行,计算它们的值等于“条件”的列数(“条件”以外的列)。 最终输出应如下所示:

我不想写一个 for 循环。

作为一种解决方案,我想用np.where 将等于“条件”的值替换为 1,将其他值替换为 0,然后将每行的 1 相加,这没有帮助:

data = pd.DataFrame(np.where(data.loc[:,data.columns != 'condition'] == data['condition'], 1, 0), columns = data.columns)

这只是一个想法(我的意思是用 1 和 0 替换值),但任何 Python 解决方案都值得赞赏。

【问题讨论】:

  • 为什么使用 0/1 而不是实际的布尔值?

标签: python pandas


【解决方案1】:

比较所有没有最后一列的列 condition 与 DataFrame.eq 并计算 Trues by sum:

data['new'] = data.iloc[:, :-1].eq(data['condition'], axis=0).sum(axis=1)

另一个想法是比较所有列与删除condition col:

data['new'] = data.drop('condition', axis=1).eq(data['condition'], axis=0).sum(axis=1)

感谢@Sayandip Dutta 的评论,您的想法是比较所有列并删除1:

data['new'] = data.eq(data['condition'], axis=0).sum(axis=1).sub(1)

print (data)
   w1  w2  w3  w4  w5  condition  new
0   0   5   0   5   7          5    2
1   1   8   0   1   1          1    3
2   0   0   0   0   0          0    5

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-07-18
    • 2022-11-14
    • 1970-01-01
    • 2019-05-29
    • 2022-01-16
    • 1970-01-01
    • 2018-07-17
    相关资源
    最近更新 更多