尝试删除重复项时,Pandas仅删除某些列值

时间:2017-05-09 18:43:50

标签: python pandas dataframe

我的问题与this one有些相似,但并不完全相同。我有一个具有以下结构的CSV

| id | entrydate  | sales | purchases |
| -- | -----------| ----- | --------- |
| 1  | 05/03/2017 | 10    | 1         |
| 2  | 05/03/2017 | 20    | 2         |
| 3  | 05/03/2017 | 30    | 3         |
| 1  | 05/03/2017 | 40    | 1         |

我将此读入数据框,我想获得每日销售和购买的汇总(个人ID并不重要,只是每日汇总)。

但是,首先,我需要删除重复项。这让我很沮丧,因为如果您采用上面的示例,对于 id 1 ,同一天有两个条目,但purchases列中的多个条目将被视为重复条目,sales列中的多个条目有效,因此正确的分组将导致

| id | entrydate  | sales | purchases |
| -- | -----------| ----- | --------- |
| 1  | 05/03/2017 | 50    | 1         |
| 2  | 05/03/2017 | 20    | 2         |
| 3  | 05/03/2017 | 30    | 3         |

然后获得每日汇总会给我

|entrydate   | sales | purchases |
| -----------| ----- | --------- |
| 05/03/2017 | 100   | 6         |

我试图使用

删除purchases重复项
df = pandas.read_csv('../my-csv.csv', parse_dates=True, dayfirst=True, usecols=my_columns, dtype=my_dtypes).rename(columns=str.lower).assign(date=lambda x: pd.to_datetime(x['entrydate'], format="%d/%m/%Y")).set_index('date')

enter image description here

df = df.drop_duplicates(['id', 'entrydate', 'purchases'])
df.drop(['id'], axis=1, inplace=True)
df = df.groupby(pd.TimeGrouper(freq='D')).sum()

虽然这会删除重复的purchases,但它也会删除有效的sales

enter image description here

A-Za-z解决方案的图像

enter image description here

3 个答案:

答案 0 :(得分:1)

如果您通过entrydate分组,则可以汇总销售和购买:

In [11]: df.groupby("entrydate").agg({"sales": "sum", "purchases": "sum"})
Out[11]:
            sales  purchases
entrydate
05/03/2017    100          7

答案 1 :(得分:1)

您可以使用groupby两次,首先是聚合销售

df.sales = df.groupby('id').sales.transform('sum')
df = df.drop_duplicates()
df.groupby(df.entrydate).sum().reset_index()


    entrydate   sales   purchases
0   2017-05-03  100     6

编辑:考虑不同日期的总和

df.sales = df.groupby(['id', 'date']).sales.transform('sum')
df = df.drop_duplicates()
df.groupby('date')['sales', 'purchases'].sum().reset_index()

你得到了

    date        sales   purchases
0   2017-03-05  100     6
1   2017-03-06  40      1

答案 2 :(得分:0)

<强>设置

df = pd.DataFrame({'entrydate': {0: '05/03/2017',
  1: '05/03/2017',
  2: '05/03/2017',
  3: '05/03/2017',
  4: '06/03/2017',
  5: '06/03/2017',
  6: '06/03/2017',
  7: '06/03/2017'},
 'id': {0: 1, 1: 2, 2: 3, 3: 1, 4: 1, 5: 2, 6: 3, 7: 1},
 'purchases': {0: 1, 1: 2, 2: 3, 3: 1, 4: 1, 5: 2, 6: 3, 7: 1},
 'sales': {0: 10, 1: 20, 2: 30, 3: 40, 4: 10, 5: 20, 6: 30, 7: 40}})

<强>解决方案

#First group by entrydate and id, summing sales and take the max from purchases(removing duplicates). Then another group by to sum sales and purchases.
df.groupby(['entrydate','id']).agg({'sales':sum, 'purchases':max}).groupby(level=0).sum().reset_index()
Out[431]: 
    entrydate  purchases  sales
0  05/03/2017          6    100
1  06/03/2017          6    100