gpt4 book ai didi

python Pandas : can we avoid apply in this case of groupby/apply?

转载 作者:行者123 更新时间:2023-11-28 22:11:44 27 4
gpt4 key购买 nike

我听说过很多关于 pandas apply 很慢的说法,应该尽可能少用。

我这里有个情况:

df = pd.DataFrame({'Date': ['2019-01-02', '2019-01-03', '2019-01-04'],
'Fund_ID': [9072, 9072, 9072],
'Fund_Series': ['A', 'A', 'A'],
'Value': [1020.0, 1040.4, 1009.188],
'Dividend': [0.0, 0.0, 52.02]})

我想在分组后做一些调整后的权重操作:

df['Pct_Change_Adjusted'] = df.groupby(['Fund_ID', 'Fund_Series'], as_index=False) \
.apply(lambda x: (x.Value + x.Dividend)/(x.Value.shift()+x.Dividend.shift()) ) \
.reset_index(drop=True).values[0]

print(df)

Date Dividend Fund_ID Fund_Series Value Pct_Change_Adjusted
0 2019-01-02 0.00 9072 A 1020.000 NaN
1 2019-01-03 0.00 9072 A 1040.400 0.02
2 2019-01-04 52.02 9072 A 1009.188 0.02

这里有没有apply的替代方法可以提高效率,或者至少有第二种方法!!

注意:我说的不是 dask 和其他并行化,而是纯 pandas。

必需:
在不使用应用的情况下计算列 Pct_Change_Adjusted

最佳答案

是的,使用 groupby.pct_change 可以 100% 向量化:

(df.Value + df.Dividend).groupby([df.Fund_ID, df.Fund_Series]).pct_change()

0 NaN
1 0.02
2 0.02
dtype: float64

df['Pct_Change_Adjusted'] = (df.assign(Foo=df['Value'] + df['Dividend'])
.groupby(['Fund_ID', 'Fund_Series'])
.Foo
.pct_change())

df

Date Fund_ID Fund_Series Value Dividend Pct_Change_Adjusted
0 2019-01-02 9072 A 1020.000 0.00 NaN
1 2019-01-03 9072 A 1040.400 0.00 0.02
2 2019-01-04 9072 A 1009.188 52.02 0.02

关于 python Pandas : can we avoid apply in this case of groupby/apply?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55484481/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com