Python 在pandas中计算和添加列的最快方法是什么?
我想在数据帧的末尾添加一列,其中包含特定值的移动平均值(EWM) 目前,我使用2个for循环:Python 在pandas中计算和添加列的最快方法是什么?,python,pandas,performance,allocation,Python,Pandas,Performance,Allocation,我想在数据帧的末尾添加一列,其中包含特定值的移动平均值(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) &
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
这真的很慢(需要几分钟-我有50000多行…):有人有更好的主意吗
非常感谢
ODO22我想在看不到数据的情况下猜一下它是如何工作的
df['EMA'] = (df.groupby([Country_Names,i_Codes])
.transform(lambda x:x.KRI_VALUE.ewm(span=6, adjust=False).mean())
我想在看不到数据的情况下猜它是怎么工作的
df['EMA'] = (df.groupby([Country_Names,i_Codes])
.transform(lambda x:x.KRI_VALUE.ewm(span=6, adjust=False).mean())
您可以共享数据样本和预期输出吗?您可能正在寻找
groupby
。您可以共享数据样本和预期输出吗?您可能正在寻找groupby
。