跨列删除具有相同单元格值的任何行

2024-09-30 20:35:15 发布

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

我找不到任何解决这个问题的方法this is the closest I guess, but I can't figure out how to implement the ideas here.

不知怎的,我发现自己看到了这样一个数据帧:

data = [['apple', 'banana','pear','mango'], ['pasta', 'pasta','pasta','pasta'], ['onion', 'tomato','celery','potato'], ['dog', 'dog','dog','dog']]
df = pd.DataFrame(data) 
df 

哪些产出:

        0   1         2     3
0   apple   banana  pear    mango
1   pasta   pasta   pasta   pasta
2   onion   tomato  celery  potato
3   dog     dog     dog     dog

第2行和第4行在所有4列中都有相同的值,我只想去掉它们,因此最终的df如下所示:

        0   1         2     3
0   apple   banana  pear    mango
1   onion   tomato  celery  potato

使用drop_duplicates()没有任何作用,因为没有重复的行。与duplicated()相同

以下是我能想到的唯一想法(如果你可以这么说的话)。如果我跑

df.transpose()

我明白了

        0   1       2        3
0   apple   pasta   onion   dog
1   banana  pasta   tomato  dog
2   pear    pasta   celery  dog
3   mango   pasta   potato  dog

现在如果我在第四列运行duplicated()

df.duplicated(3)

我明白了

0    False
1     True
2     True
3     True
dtype: bool

因此,也许我可以想出一个函数来转换df,在每列上运行duplicated(),如果除第一个以外的所有值都返回为True,则删除该列,然后将df转换回其原始形状

但我不知道怎么做;另外,我想知道是否有更优雅的方式到达同一个地方


Tags: thetrueappledfdatapotatocelerybanana
1条回答
网友
1楼 · 发布于 2024-09-30 20:35:15

您可以沿axis=1使用^{},并检查所有列的唯一值超过1的行:

每个文档:nunique()

Count distinct observations over requested axis.

因此,如果我们测试:

df.nunique(1)

这将产生:

0    4
1    1
2    4
3    1

自然地

df.nunique(1)>1

将返回:

0     True
1    False
2     True
3    False

因此,在^{}的帮助下,我们可以:

df[df.nunique(1)>1]

返回所需的输出:

       0       1       2       3
0  apple  banana    pear   mango
2  onion  tomato  celery  potato

相关问题 更多 >