【问题标题】:What is the fastest way to calculate and add a column in pandas?在熊猫中计算和添加列的最快方法是什么?
【发布时间】:2019-07-23 10:20:31
【问题描述】:

我想在包含特定值的移动平均值 (EWM) 的数据框末尾添加一列。

目前,我正在使用 2 个 for 循环:

for country in Country_Names:
 for i in i_Codes:
    EMA = df[(df['COUNTRY_NAME']==country) & (df['I_CODE']==i)].KRI_VALUE.ewm(span=6, adjust=False).mean()
    df.loc[(df['COUNTRY_NAME']==country) & (df['I_CODE']==i), 'EMA'] = EMA

这真的很慢(需要几分钟 - 我有超过 50,000 行...):有人有更好的主意吗?

非常感谢!

ODO22

【问题讨论】:

  • 您能否分享您的数据样本和预期输出?
  • 您可能正在寻找groupby

标签: python pandas performance allocation


【解决方案1】:

我会在没有看到数据的情况下猜测它是如何工作的,

df['EMA'] = (df.groupby([Country_Names,i_Codes])
               .transform(lambda x:x.KRI_VALUE.ewm(span=6, adjust=False).mean())

【讨论】:

    猜你喜欢
    • 2022-06-15
    • 2013-12-03
    • 2023-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-27
    • 2022-01-06
    • 1970-01-01
    相关资源
    最近更新 更多