根据ID删除数据框中列中的重复值

时间:2017-10-26 14:28:53

标签: python pandas

我正在数百万行的数据框上执行数据清理。 它看起来像这样的例子:

    id   transaction_date  expire_date
0   A    2015-01-01        2015-02-01
1   A    2015-01-01        2015-03-14
2   A    2015-01-01        2015-06-19
3   A    2015-01-01        2015-07-01
4   B    2016-02-02        2016-03-02
5   C    2016-01-01        2016-01-15

我想从第0行删除到第3行,因为同一天有不同过期日期的许多交易都没有意义。

我在想这个

df.drop_duplicates(subset='transaction_date')

这是正确的方法吗?

1 个答案:

答案 0 :(得分:0)

这取决于你的需要:

#if need check all duplicates per id and transaction_date and drop them
df = df.drop_duplicates(subset=['id','transaction_date'],keep=False)
print (df)
  id transaction_date expire_date
4  B       2016-02-02  2016-03-02
5  C       2016-01-01  2016-01-15

如果需要检查expire_date并删除所有不同日期的所有欺骗行:

#check count per group and count unique values in expire_date
df1 = df.groupby(['id', 'transaction_date'])
        .agg({'transaction_date':'size', 'expire_date':'nunique'})
 #get all same count, but remove unique rows
mask = (df1['transaction_date'] == df1['expire_date']) & (df1['transaction_date'] > 1)

#create mask by join to original df
m = df.join(mask.rename('m'), on=['id','transaction_date'])['m']
print (m)
0     True
1     True
2     True
3     True
4    False
5    False
Name: m, dtype: bool

 #last filter by inverting mask by ~
df = df[~m]
print (df)
  id transaction_date expire_date
4  B       2016-02-02  2016-03-02
5  C       2016-01-01  2016-01-15
相关问题