【问题标题】:Speed Up Pandas Iterations加速 Pandas 迭代
【发布时间】:2020-09-25 14:08:42
【问题描述】:

我有 DataFrame,它由 3 列组成:CustomerId、Amount 和 Status(成功或失败)。 DataFrame 没有以任何方式排序。一个 CustomerId 可以在 DataFrame 中重复多次。

我想用以下逻辑在这个 DataFrame 中引入新列:

df[totalamount]= 状态为成功的每个客户的金额总和。

我已经有一个正在运行的代码,但是使用 df.iterrows 需要太多时间。因此请求您提供替代方法,如 pandas 矢量化或 numpy 矢量化。

例如,我想从前三列创建“totalamount”列:

   CustomerID  Amount   Status  totalamount
0           1       5  Success          105 # since both transatctions were successful
1           2      10   Failed           80 # since one transaction was successful
2           3      50  Success           50
3           1     100  Success          105
4           2      80  Success           80
5           4      60   Failed            0

【问题讨论】:

    标签: python-3.x pandas dataframe data-analysis


    【解决方案1】:

    使用whereNaN 屏蔽“失败”行,同时保留DataFrame 的长度。然后groupby CustomerID 和transform 'Amount' 列的总和将结果返回到每一行。

    df['totalamount'] = (df.where(df['Status'].eq('Success'))
                           .groupby(df['CustomerID'])['Amount']
                           .transform('sum'))
    
       CustomerID  Amount   Status  totalamount
    0           1       5  Success        105.0
    1           2      10    Faled         80.0
    2           3      50  Success         50.0
    3           1     100  Success        105.0
    4           2      80  Success         80.0
    5           4      60   Failed          0.0
    

    使用where(而不是子集DataFrame)的原因是因为groupby + sum默认将整个NaN组相加为0,所以我们不需要任何额外的东西来处理CustomerID 4,因为实例。

    【讨论】:

      【解决方案2】:
      df_new = df.groupby(['CustomerID', 'Status'], sort=False)['Amount'].sum().reset_index()
      df_new = (df_new[df_new['Status'] == 'Success']
                  .drop(columns='Status')
                  .rename(columns={'Amount': 'totalamount'}))
      df = pd.merge(df, df_new , on=['CustomerID'], how='left')
      

      我完全不确定,但我认为这可能有效

      【讨论】:

        猜你喜欢
        • 2017-09-17
        • 1970-01-01
        • 2011-10-03
        • 2022-01-18
        • 2018-11-15
        • 2020-12-17
        • 1970-01-01
        • 2020-07-14
        • 1970-01-01
        相关资源
        最近更新 更多