[英]Python: How to remove rows where multiple columns have equal values?
I want to remove rows where multiple columns have the same values.我想删除多列具有相同值的行。 I read this question about two columns and tried to extend to multiple columns, however I get an error.
我阅读了有关两列的问题并尝试扩展到多列,但是出现错误。
Here is some sample data, similar to my dataframe:这是一些示例数据,类似于我的数据框:
import pandas as pd
data = [['table1',10,8,7],['table2',3,3,3],['table3',3,8,11],['table4',12,12,12],['table5',13,15,5]]
df = pd.DataFrame(data,columns=['table_name','Attr1','Attr2','Attr3'])
and my desired result和我想要的结果
res = [['table1',10,8,7],['table3',3,8,11],['table5',13,15,5]]
result = pd.DataFrame(res,columns=['table_name','Attr1','Attr2','Attr3'])
I tried我试过
[df[df['Attr1'] != df['Attr2'] | df['Attr1'] != df['Attr3'] | df['Attr2'] != df['Attr3']]]
which retrieves the error检索错误
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
Any ideas?有任何想法吗?
使用 df.query:
df = df.query("Attr1 != Attr2 != Attr3")
Use DataFrame.ne
for compare all values by Attr1
column and test if at least one True
per row by DataFrame.any
, last filter by boolean indexing
:使用
DataFrame.ne
用于比较的所有值Attr1
柱和测试,如果至少一个True
每行通过DataFrame.any
,由最后一个过滤器boolean indexing
:
df = df[df[['Attr1','Attr2','Attr3']].ne(df['Attr1'], axis=0).any(axis=1)]
print (df)
table_name Attr1 Attr2 Attr3
0 table1 10 8 7
2 table3 3 8 11
4 table5 13 15 5
Details :详情:
print (df[['Attr1','Attr2','Attr3']].ne(df['Attr1'], axis=0))
Attr1 Attr2 Attr3
0 False True True
1 False False False
2 False True True
3 False False False
4 False True True
print (df[['Attr1','Attr2','Attr3']].ne(df['Attr1'], axis=0).any(axis=1))
0 True
1 False
2 True
3 False
4 True
dtype: bool
Another solution is test number of unique values by DataFrame.nunique
:另一种解决方案是通过
DataFrame.nunique
测试唯一值的DataFrame.nunique
:
df = df[df[['Attr1','Attr2','Attr3']].nunique(axis=1).ne(1)]
You can create conditions for each and then perform your comparison:您可以为每个创建条件,然后进行比较:
c1 = df['Attr1'].ne(df['Attr2'])
c2 = df['Attr1'].ne(df['Attr3'])
c3 = df['Attr2'].ne(df['Attr3'])
>>> df[c1 | c2 | c3]
table_name Attr1 Attr2 Attr3
0 table1 10 8 7
2 table3 3 8 11
4 table5 13 15 5
Each condition will be a series indicating whether or not the inequality holds, eg每个条件将是一系列指示不等式是否成立,例如
>>> c1
0 True
1 False
2 True
3 False
4 True
dtype: bool
>>> c1 | c2 | c3
0 True
1 False
2 True
3 False
4 True
dtype: bool
布尔索引,条件是轴 1 上唯一值的数量必须等于DataFrame
的宽度:
df = df[df.nunique(axis=1).eq(df.shape[1])]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.