从熊猫数据框中删除重复项,同时保留多数元素

时间:2020-01-23 18:09:29

标签: python pandas

我有一个熊猫数据框,如下所示:

   Cat  Date
1  A    2019-12-30
2  A    2019-12-30
3  A    2020-12-30
4  A    2020-01-06
5  A    2020-01-06
6  B    2020-01-06
7  B    2020-01-13
8  B    2020-01-13
9  A    2020-01-13
 .    .
 .    .
 .    .

在“日期”列中有重复的日期,我想向数据框架“下沉”,以便删除所有重复的日期。但是,要确定此“冒出”之后“猫”列中的内容,我想选择被“冒出”的日期的多数元素。

因此,我希望输出为:

   Cat  Date
1  A    2019-12-30
2  A    2020-01-06
3  B    2020-01-13
 .    .
 .    .
 .    .

效率很重要,因为我的DataFrame非常大(100k行),所以我希望能够尽快做到这一点。可以保证重复的日期数始终是奇数,并且不同的“ Cat”字母总数最多可以为2,因此不必担心联系。

3 个答案:

答案 0 :(得分:3)

尝试value_countsdate列上的groupby之后的所有值进行计数:

df.groupby("Date").agg(lambda x: x.value_counts().index[0])
#            Cat
# Date
# 2019-12-30   A
# 2020-01-06   A
# 2020-01-13   B
# 2020-12-30   A

说明

  1. 使用groupby根据Date将数据帧分组。

  2. 使用agg应用聚合。此函数接受用于汇总组的函数。

  3. 定义聚合函数:

    3.1。使用value_counts函数获取每组的值数:

print(df.groupby("Date").agg(lambda x: x.value_counts()))
#                Cat
# Date
# 2019-12-30       2
# 2020-01-06  [3, 2]
# 2020-01-13  [2, 1]
# 2020-12-30       1

注意:value_counts方法的结果是一个有序系列。

3.2。但是,我们实际上需要values而不是count。诀窍是在意甲上使用index

print(df.groupby("Date").agg(lambda x: x.value_counts().index))
#                Cat
# Date
# 2019-12-30       A
# 2020-01-06  [B, A]
# 2020-01-13  [B, A]
# 2020-12-30       A

3.3。最后,选择第一个值:

print(df.groupby("Date").agg(lambda x: x.value_counts().index[0]))
#            Cat
# Date
# 2019-12-30   A
# 2020-01-06   B
# 2020-01-13   B
# 2020-12-30   A

答案 1 :(得分:2)

这是一个简单的解决方案

def removeDuplicatesKeepBest(df):
    # sort the data frame 
    df.sort_values(by="Cat")
    # Look only in the date column and only keep the first occurence if there is a dulplicate
    df.drop_duplicates(subset = "Date" , keep = 'first', inplace = True)

    return df

希望这会有所帮助!

答案 2 :(得分:1)

我会考虑使用旧的groupby

df.groupby(["Cat", "Date"]).size()\
  .reset_index(name="to_drop")\
  .drop("to_drop", axis=1)

或者,您也可以使用两列的重复副本

df.drop_duplicates(['Date',"Cat"])