我有一个 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]})
Run Code Online (Sandbox Code Playgroud)
我需要有一列,为每一行计算列数(“条件”以外的列),它们的值等于“条件”。最终输出应如下所示:
我不想写for循环。
作为一种解决方案,我想将等于“条件”的值替换为 1,将其他值替换为 0,np.where如下所示,然后将每行的 1 相加,这没有帮助:
data = pd.DataFrame(np.where(data.loc[:,data.columns != 'condition'] == data['condition'], 1, 0), columns = data.columns)
Run Code Online (Sandbox Code Playgroud)
这只是一个想法(我的意思是用 1 和 0 替换这些值),但任何 Pythonic 解决方案都值得赞赏。
比较所有没有 last by column 的列condition,DataFrame.eq并计算Trues by sum:
data['new'] = data.iloc[:, :-1].eq(data['condition'], axis=0).sum(axis=1)
Run Code Online (Sandbox Code Playgroud)
另一个想法是将所有列与 remove conditioncol进行比较:
data['new'] = data.drop('condition', axis=1).eq(data['condition'], axis=0).sum(axis=1)
Run Code Online (Sandbox Code Playgroud)
感谢您的评论@Sayandip Dutta,您的想法是比较所有列并删除1:
data['new'] = data.eq(data['condition'], axis=0).sum(axis=1).sub(1)
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
182 次 |
| 最近记录: |