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

标签 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)

最佳答案

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

关于python - 删除重复行,如果包含所有相同的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45701346/

相关文章:

python - 在 python 中加载 Tensorflow Lite 模型

python - 对象名称中不允许使用 ``/`` 字符

python - pandas中如何比较workers时间范围内的事务时间点将员工添加到事务表中?

用于连接字典的键和值的 Pythonic 语法

python - 使用 numba jit 提高 python 脚本的性能

具有 doctests、覆盖率和并行性的 Python 测试发现

python - 按索引和列排序

python - 使用 xlsxwriter 写入时设置货币符号

Python/ Pandas : Dataframe subset by filter criteria

excel - 将数据框写入现有 Excel 文件中的多个工作表。打开excel文件时得到 'We Found Problem with some content in X.xlsx'