如何从周期性列和列的总和中提取百分比列?

How to extract a percentage column from a periodic column and the sum of the column?

我有一个看起来像这样的矩阵 pandas.DataFrame:

  Store Sales   year  month day
0   1   5263    2015    7   31
1   1   5020    2015    7   30
2   1   4782    2015    7   29
3   2   5011    2015    7   28
4   2   6102    2015    7   27
[986159 rows x 5 columns]

在我做了一些转换后,我得到了每个商店的总销售额:

train['StoreTotalSales'] = train.groupby('Store')['Sales'].transform('sum')

但现在我需要遍历train.groupby(['Store', 'day', 'month'])的每一行,然后将groupby的每一行的Sales数字除以StoreTotalSales

我试过以下方法:

train['PercentSales'] = train.groupby(['Store','day', 'month'])['Sales'].transform(lambda x: x /float(x.sum()))

但是 return 新的 PercentSales 列全为 1:

  Store Sales   year  month day StoreTotalSales PercentSales
0   1   5263    2015    7   31  26178                1
1   1   5020    2015    7   30  26178                1
2   1   4782    2015    7   29  26178                1
3   2   5011    2015    7   28  12357                1
4   2   6102    2015    7   27  12357                1

但 PercentSales 行应该是:

0    5263/26178
1    5020/26178
2    4782/26178
3    5011/12357
4    6012/12357

为什么另一个 groupby 的并发症?如果你只想将列除以组总和,你可以简单地做:

train['PercentSales'] = train.groupby('Store')['Sales'].transform(lambda x: x/x.sum())

或者等效地,按照您的方法:

train['StoreTotalSales'] = train.groupby('Store'['Sales'].transform('sum')
train['PercentSales'] = train['Sales']/train['StoreTotalSales']

如果您 运行 遇到其他问题,请告诉我。