【问题标题】:Python / Pandas - performance - trying to skip a for loop in a full column operationPython / Pandas - 性能 - 尝试在整列操作中跳过 for 循环
【发布时间】:2017-12-02 04:06:35
【问题描述】:

我有一个名为 target 的数据框:

target:

          group  estimation_error
170  64.22-1-00          0.061829
72   64.22-1-00          2.242214
121  35.12-3-00         31.960277
99   64.22-1-00          4.819315
19   35.12-3-00          0.850597

我想创建一个名为group_error 的新列,它是同一组的行的误差中位数。它看起来像这样:

          group  estimation_error median_group_error
170  64.22-1-00          0.061829           2.242214
72   64.22-1-00          2.242214           2.242214
121  35.12-3-00         31.960277          16.405437
99   64.22-1-00          4.819315           2.242214
19   35.12-3-00          0.850597          16.405437

我可以通过以下方式做到这一点:

target['group_median_error']=""
groups=target.groupby('group')

for i in target.index:
    try:
        target['group_median_error'][i]=(groups.get_group(target.group[i])).estimation_error.median()
    except KeyError:
        pass

但是,由于这是一个大型数据框,因此需要的时间太长。我相信,如果我可以跳过 for 循环,我将获得可观的性能提升。

为此,我尝试将for 循环替换为以下内容:

target['group_median_error']=(groups.get_group(target.group)).estimation_error.median()

但是它让我遇到以下错误:

TypeError: 'Series' objects are mutable, thus they cannot be hashed

比我来的问题:

  • 有没有办法在不经过for 循环的情况下执行相同的操作?
  • 跳过该循环会提高性能吗?

【问题讨论】:

    标签: python performance pandas for-loop


    【解决方案1】:

    我们可以用矢量化(不循环)的方式来做:

    In [11]: df['median_group_error'] = \
                df.groupby('group')['estimation_error'].transform('median')
    
    In [12]: df
    Out[12]:
              group  estimation_error  median_group_error
    170  64.22-1-00          0.061829            2.242214
    72   64.22-1-00          2.242214            2.242214
    121  35.12-3-00         31.960277           16.405437
    99   64.22-1-00          4.819315            2.242214
    19   35.12-3-00          0.850597           16.405437
    

    【讨论】:

    • 变换内部不应该是“中位数”而不是“平均值”?
    • @abutremutante,很好,谢谢!我已经更正了答案
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-04
    • 2016-06-12
    • 2010-12-31
    • 2013-02-01
    • 2021-08-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多