gpt4 book ai didi

python - Pandas pct_change() 反向

转载 作者:太空宇宙 更新时间:2023-11-03 13:09:23 26 4
gpt4 key购买 nike

假设我们有一个数据框,我们计算行之间的百分比变化

y_axis = [1,2,3,4,5,6,7,8,9]
x_axis = [100,105,115,95,90,88,110,100,0]

DF = pd.DataFrame({'Y':y_axis, 'X':x_axis})

DF = DF[['Y','X']]
DF['PCT'] = DF['X'].pct_change()

Y X PCT
0 1 100 NaN
1 2 105 0.050000
2 3 115 0.095238
3 4 95 -0.173913
4 5 90 -0.052632
5 6 88 -0.022222
6 7 110 0.250000
7 8 100 -0.090909
8 9 0 -1.000000

这样它就从第一行开始。我想从最后一行开始计算 pct_change()

一种方法

DF['Reverse'] = list(reversed(x_axis))
DF['PCT_rev'] = DF['Reverse'].pct_change()
pct_rev = DF.PCT_rev.tolist()

DF['_PCT_'] = list(reversed(pct_rev))
DF2 = DF[['Y','X','PCT','_PCT_']]

Y X PCT _PCT_
0 1 100 NaN -0.047619
1 2 105 0.050000 -0.086957
2 3 115 0.095238 0.210526
3 4 95 -0.173913 0.055556
4 5 90 -0.052632 0.022727
5 6 88 -0.022222 -0.200000
6 7 110 0.250000 0.100000
7 8 100 -0.090909 inf
8 9 0 -1.000000 NaN

但这是一个非常丑陋且低效的解决方案。我想知道是否有更优雅的解决方案?

最佳答案

DF.assign(_PCT_=DF.X.pct_change(-1))

Y X PCT _PCT_
0 1 100 NaN -0.047619
1 2 105 0.050000 -0.086957
2 3 115 0.095238 0.210526
3 4 95 -0.173913 0.055556
4 5 90 -0.052632 0.022727
5 6 88 -0.022222 -0.200000
6 7 110 0.250000 0.100000
7 8 100 -0.090909 inf
8 9 0 -1.000000 NaN

Series.pct_change(periods=1, fill_method='pad', limit=None, freq=None, **kwargs)

periods : int, default 1 Periods to shift for forming percent change

https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.pct_change.html

关于python - Pandas pct_change() 反向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47647410/

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