如何从跨多个列具有重复字符串的数据帧中删除行?

2024-10-04 09:18:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个包含多个列的dataframe,这些列必须都是唯一的字符串才能使特定行有效(即,在下面的示例中,我有4列,因此必须有4个唯一的值)。因此,我想删除任何列中包含重复字符串的行

感觉应该是直截了当的,但我想不出来。非常感谢您的帮助

import pandas as pd

df = pd.DataFrame([['a','b','c','d'],['a','c','d','c'],['b','a','e','g'],['a','a','c','f'],['b','c','b','d']],columns=['Pos1','Pos2','Pos3','Pos4'])


print(df)

  Pos1 Pos2 Pos3 Pos4
0    a    b    c    d
1    a    c    d    c
2    b    a    e    g
3    a    a    c    f
4    b    c    b    d


The output I want will drop row index 1 ('c' is repeated), row index 3 ('a' is repeated) and row index 4 ('b' is repeated)


  Pos1 Pos2 Pos3 Pos4
0    a    b    c    d
2    b    a    e    g

Tags: 字符串import示例dataframedfindexisrepeated
1条回答
网友
1楼 · 发布于 2024-10-04 09:18:02

^{}检查每行的唯一值数,并按^{}==)的列数比较按^{}筛选的值:

df = df[df.nunique(axis=1).eq(len(df.columns))]
print (df)
  Pos1 Pos2 Pos3 Pos4
0    a    b    c    d
2    b    a    e    g

相关问题 更多 >