Pandas在交叉值中找到Duplicates

max*_*zin 5 python duplicates pandas

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

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
Run Code Online (Sandbox Code Playgroud)

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

df_new
Out[20]: 
   a  b  c  d
1  x  y  e  f
3  w  v  s  t
Run Code Online (Sandbox Code Playgroud)

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

jez*_*ael 4

我认为您需要使用withboolean indexing创建的掩码进行过滤,以反转它使用:numpy.sortduplicated~

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
Run Code Online (Sandbox Code Playgroud)

细节:

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
Run Code Online (Sandbox Code Playgroud)