Pandas 发现交叉值中的重复项

2023-11-24

我有一个数据框,想要消除具有相同值但在不同列中的重复行:

df = pd.DataFrame(columns=['a','b','c','d'], index=['1','2','3'])
df.loc['1'] = pd.Series({'a':'x','b':'y','c':'e','d':'f'})
df.loc['2'] = pd.Series({'a':'e','b':'f','c':'x','d':'y'})
df.loc['3'] = pd.Series({'a':'w','b':'v','c':'s','d':'t'})

df
Out[8]: 
   a  b  c  d
1  x  y  e  f
2  e  f  x  y
3  w  v  s  t

行 [1],[2] 具有值 {x,y,e,f},但它们排列成十字形 - 即,如果您将行 [2] 中的列 c,d 与 a,b 交换,您将得到重复的。 我想删除这些行并只保留一行,以获得最终输出:

df_new
Out[20]: 
   a  b  c  d
1  x  y  e  f
3  w  v  s  t

我怎样才能有效地实现这一目标?


我认为你需要过滤boolean indexing带有由创建的蒙版numpy.sort with duplicated,为了反转它使用~:

df = df[~pd.DataFrame(np.sort(df, axis=1), index=df.index).duplicated()]
print (df)
   a  b  c  d
1  x  y  e  f
3  w  v  s  t

Detail:

print (np.sort(df, axis=1))
[['e' 'f' 'x' 'y']
 ['e' 'f' 'x' 'y']
 ['s' 't' 'v' 'w']]

print (pd.DataFrame(np.sort(df, axis=1), index=df.index))
   0  1  2  3
1  e  f  x  y
2  e  f  x  y
3  s  t  v  w

print (pd.DataFrame(np.sort(df, axis=1), index=df.index).duplicated())
1    False
2     True
3    False
dtype: bool

print (~pd.DataFrame(np.sort(df, axis=1), index=df.index).duplicated())

1     True
2    False
3     True
dtype: bool
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Pandas 发现交叉值中的重复项 的相关文章