比较所有行的多个特定列 [英] compare multiple specific columns of all rows

查看:80
本文介绍了比较所有行的多个特定列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想比较所有行中的特定列,如果它们是唯一的,则将值提取到新列中,否则为0.

I want to compare the particular columns of all the rows, if they are unique extract the value to the new column otherwise 0.

如果示例日期框架如下:

If the example dateframe as follows:

A      B      C  D  E  F
13348  judte  1  1  1  1
54871  kfzef  1  1  0  1
89983  hdter  4  4  4  4
7543   bgfd   3  4  4  4

结果应如下:

A      B      C  D  E  F Result
13348  judte  1  1  1  1  1
54871  kfzef  1  1  0  1  0
89983  hdter  4  4  4  4  4
7543   bgfd   3  4  4  4  0

我很高兴听到一些建议.

I am pleased to hear some suggestions.

推荐答案

使用:

cols = ['C','D','E','F']

df['Result'] = np.where(df[cols].eq(df[cols[0]], axis=0).all(axis=1), df[cols[0]], 0)
print (df)
       A      B  C  D  E  F  Result
0  13348  judte  1  1  1  1       1
1  54871  kfzef  1  1  0  1       0
2  89983  hdter  4  4  4  4       4
3   7543   bgfd  3  4  4  4       0

详细信息:

首先比较按然后通过

Then check if all Trues per row by all:

print (df[cols].eq(df[cols[0]], axis=0).all(axis=1))
0     True
1    False
2     True
3    False
dtype: bool

最后一次使用 numpy.where True分配第一列值,为False分配0.

And last use numpy.where for assign first column values for Trues and 0 for False.

这篇关于比较所有行的多个特定列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆