python-3.x 使用NaN计算pct_change时如何避免bfill或fill

jvidinwx  于 2023-02-10  发布在  Python
关注(0)|答案(1)|浏览(162)

对于如下所示的df,我使用pct_change()来计算滚动百分比变化:

price = [np.NaN, 10, 13, np.NaN, np.NaN, 9]
df = pd. DataFrame(price, columns = ['price'])
df
Out[75]:
    price
0 NaN
1 10.0
2 13.0
3 NaN
4 NaN
5 9.0

但我得到了这些意想不到的结果:

df.price.pct_change(periods = 1, fill_method='bfill')
Out[76]:
0 NaN
1 0.000000
2 0.300000
3 -0.307692
4 0.000000
5 0.000000
Name: price, dtype: float64

df.price.pct_change(periods = 1, fill_method='pad')
Out[77]:
0 NaN
1 NaN
2 0.300000
3 0.000000
4 0.000000
5 -0.307692
Name: price, dtype: float64

df.price.pct_change(periods = 1, fill_method='ffill')
Out[78]:
0 NaN
1 NaN
2 0.300000
3 0.000000
4 0.000000
5 -0.307692
Name: price, dtype: float64

我希望在使用NaN s进行计算时,结果将是NaN s,而不是向前或向后填充,然后再进行计算。
我能问一下如何实现吗?谢谢。
预期结果:

0 NaN
1 NaN
2 0.300000
3 NaN
4 NaN
5 NaN
Name: price, dtype: float64

参考:
https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.pct_change.html

uoifb46i

uoifb46i1#

也许您可以使用diffshift手动计算pct:

period = 1
pct = df.price.diff().div(df.price.shift(period))
print(pct)

# Output
0    NaN
1    NaN
2    0.3
3    NaN
4    NaN
5    NaN
Name: price, dtype: float64

更新:您可以传递fill_method=None

period = 1
pct = df.price.pct_change(periods=period, fill_method=None)
print(pct)

# Output
0    NaN
1    NaN
2    0.3
3    NaN
4    NaN
5    NaN
Name: price, dtype: float64

相关问题