删除重复行,如果包含所有相同的值

时间:2017-08-15 20:52:40

标签: python pandas

我有Dataframe如下:

df = pd.DataFrame({'first' : ['John', 'Mary','Peter'],
                      'last' : ['Mary', 'John','Mary']})

df
Out[700]: 
   first  last
0   John  Mary
1   Mary  John
2  Peter  Mary

我想在行包含相同值时删除副本 在这种情况下,预期的输出将是:

   first  last  
0   John  Mary  
2  Peter  Mary 

到目前为止,我的方法如下:

df['DropKey']=df.apply(lambda x: ''.join(sorted(pd.Series(x))),axis=1)
df.drop_duplicates('DropKey')

有没有有效的方法来实现这一目标?

我的实际数据大小:

df.shape
Out[709]: (10000, 607)

1 个答案:

答案 0 :(得分:4)

In [13]: pd.DataFrame(np.sort(df.values, axis=1), columns=df.columns).drop_duplicates()
Out[13]:
  first   last
0  John   Mary
2  Mary  Peter

或:

In [18]: df.values.sort(axis=1)  # NOTE: it sorts DF in-place

In [19]: df
Out[19]:
  first   last
0  John   Mary
1  John   Mary
2  Mary  Peter

In [20]: df.drop_duplicates()
Out[20]:
  first   last
0  John   Mary
2  Mary  Peter
相关问题