在 pandas 中计算和添加列的最快方法是什么?

What is the fastest way to calculate and add a column in pandas?

我想在包含特定值的移动平均值 (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

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

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