【问题标题】:Pandas, remove duplicates by column which duplicate N times [duplicate]熊猫,按重复N次的列删除重复项[重复]
【发布时间】:2020-02-20 11:59:06
【问题描述】:

这里是一个例子:

df = pd.DataFrame({
    'file': ['file1','file1','file1','file1','file2','file3','file4','file4','file4','file4'],
    'text': ['Text1','Text2','Text3','Text4','Text5','Text6','Text7','Text8','Text9','Text10'],
})

我需要删除“文件”重复 4 次的行,所以在本例中,我需要删除 file = file1 和 file4 的行

【问题讨论】:

标签: python pandas dataframe


【解决方案1】:

使用GroupBy.transform 获取每组值的计数,因此可以按boolean indexing 过滤:

df1 = df[df.groupby('file')['file'].transform('size') != 4]

解释:对于使用transform,必须在groupby 之后指定一些列进行计数 - 如果使用size,如果使用DataFrame 的任何列,它的工作方式相同,并且它返回具有相同的新列(Series)大小类似于由计数填充的原始 DataFrame:

print (df.groupby('file')['file'].transform('size'))
0    4
1    4
2    4
3    4
4    1
5    1
6    4
7    4
8    4
9    4
Name: file, dtype: int64

或者使用DataFrameGroupBy.filter - 如果数据量大,性能应该会更慢:

df1 = df.groupby('file').filter(lambda x: len(x) != 4)

或者Series.mapSeries.value_counts

df1 = df[df['file'].map(df['file'].value_counts()) != 4]

print (df)
    file   text
4  file2  Text5
5  file3  Text6

【讨论】:

  • 您能解释一下第一个变体,请解释一下这是如何工作的,尤其是 ('file)['file']?
  • @Contra111 - 稍等一下,我会添加解释。
【解决方案2】:

GroupBytransform 一起使用:

df[df.groupby('file').text.transform('size').ne(4)]

   file   text
4  file2  Text5
5  file3  Text6

【讨论】:

    猜你喜欢
    • 2019-02-23
    • 2019-04-12
    • 1970-01-01
    • 2023-03-31
    • 2016-01-30
    • 2018-08-03
    • 2017-03-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多