【问题标题】:Dynamic Sum in PandasPandas 中的动态总和
【发布时间】:2017-05-10 03:11:14
【问题描述】:

我有一个包含 ['customer_id'、'date'、'item_code' 和 'amount'] 的杂货交易数据框。

我想将同一天的多笔交易组合成 1 笔交易,其中包含这些单独交易的总和。例如,如果我在 1-1-16 购买了 3 件商品,每件价格为 5 美元、10 美元和 15 美元,我希望将其表示为价值 30 美元的单行。

那部分是一个简单的groupby

df.groupby(['customer_id', 'date'])['amount'].sum()

我的问题是我想创建一个名为“transaction_type”的新列,它将代码('grpd')分配给一行如果该行已分组,以及item_code的对应值如果没有分组。

因此,如果我在 1-1-16 购买了 3 件商品,但在 1-2-16 购买了一件新商品,我希望我的 customer_id 在数据框中显示 2 行。一个用于 1-1-16,在新的 transaction_type 列中具有自定义“grpd”值,另一个用于 1-2-16,将 item_code 列中的原始值复制到 transaction_type 列中。因此,对于我的交易,我的数据框最终看起来像这样:

customer_id     date    transaction_type   amount
  4231         1-1-16        grpd           $30
  4231         1-2-16        candy          $5

【问题讨论】:

  • 你能发布一个源数据集吗?

标签: python pandas dataframe


【解决方案1】:

创建虚拟数据:

df = pd.DataFrame({'customer_id':['4231']*4,'date':['1-1-2016','1-1-2016','1-1-2016','1-2-2016'],'items':['gum','candy','soda','candy'],'amount':[9,11,10,5]})

输入:

   amount customer_id      date  items
0       9        4231  1-1-2016    gum
1      11        4231  1-1-2016  candy
2      10        4231  1-1-2016   soda
3       5        4231  1-2-2016  candy

使用.agg、np.where和size:

df_out = (df.groupby(['customer_id','date'])
    .agg({'items': lambda x: np.where(x.size > 1,'grpd',x.min()),'amount':'sum'})
    .reset_index()
    .rename(columns={'items':"transaction_type"}))

输出:

  customer_id      date  amount transaction_type
0        4231  1-1-2016      30             grpd
1        4231  1-2-2016       5            candy

【讨论】:

    【解决方案2】:

    您也可以按transaction_type 分组:

    df.groupby(['date', 'customer_id', 'transaction_type'])['amount'].sum()
    

    【讨论】:

      猜你喜欢
      • 2022-11-30
      • 1970-01-01
      • 2017-05-16
      • 1970-01-01
      • 1970-01-01
      • 2019-11-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多