删除一列中的值等于另一列中的值的行 [英] Remove rows where value in one column equals value in another
本文介绍了删除一列中的值等于另一列中的值的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在努力找出如何从其中两个指定列在一行中具有相同值的pandas数据框中删除行的方法.
I'm struggling to figure out how to remove rows from a pandas dataframe in which two specified columns have the same value across a row.
例如,在以下示例中,我要删除第2列和第4列中具有重复值的行.
For example, in the below examples I would like to remove the rows which have duplicate values in the columns 2 and 4.
例如:
Column1 Column2 Column3 Column4
Pat 123 John 456
Pat 123 John 345
Jimmy 678 Mary 678
Larry 678 James 983
将变成:
Column1 Column2 Column3 Column4
Pat 123 John 456
Pat 123 John 345
Larry 678 James 983
感谢您的帮助,谢谢!
推荐答案
Series.ne
(!=
)
df[df['Column2'] != df['Column4']]
Column1 Column2 Column3 Column4
0 Pat 123 John 456
1 Pat 123 John 345
3 Larry 678 James 983
或者,使用operator.ne
:
df[operator.ne(df['Column2'], df['Column4'])]
Column1 Column2 Column3 Column4
0 Pat 123 John 456
1 Pat 123 John 345
3 Larry 678 James 983
比较两者;得到一个面具,然后过滤.
Compare the two; get a mask, then filter.
使用loc
,我们还可以提供回调(由@ W-B建议!).
With loc
, we can also supply a callback (suggested by @W-B!).
df.loc[lambda x : x['Column2'] != x['Column4']]
Column1 Column2 Column3 Column4
0 Pat 123 John 456
1 Pat 123 John 345
3 Larry 678 James 983
query
query
df.query('Column2 != Column4')
Column1 Column2 Column3 Column4
0 Pat 123 John 456
1 Pat 123 John 345
3 Larry 678 James 983
np.vectorize
np.vectorize
import operator
f = pd.np.vectorize(lambda x, y: x != y)
df[f(df['Column2'], df['Column4'])]
Column1 Column2 Column3 Column4
0 Pat 123 John 456
1 Pat 123 John 345
3 Larry 678 James 983
...只是为了好玩.
...Just for fun.
df[[x != y for x, y in zip(df['Column2'], df['Column4'])]]
Column1 Column2 Column3 Column4
0 Pat 123 John 456
1 Pat 123 John 345
3 Larry 678 James 983
比您想象的要快!
这篇关于删除一列中的值等于另一列中的值的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文