4 回答
TA贡献1807条经验 获得超9个赞
用shift
在系列上。
d = final_df['nav'] / final_df['nav'].shift(-1)
不过,您必须弄清楚如何处理最后一项,因为没有什么可除的。
TA贡献1842条经验 获得超12个赞
尝试除以移位
from pandas import pandas as pd
final_df = pd.DataFrame({"Col1": [10, 20, 15, 30, 45],
"Col2": [13, 23, 18, 33, 48],
"nav": [3, 6, 9, 27, 108]},
index=pd.date_range("2020-01-01", "2020-01-05"))
final_df["change"] = final_df["nav"].div(final_df["nav"].shift(1))
print(final_df)
Col1 Col2 nav change
2020-01-01 10 13 3 NaN
2020-01-02 20 23 6 2.0
2020-01-03 15 18 9 1.5
2020-01-04 30 33 27 3.0
2020-01-05 45 48 108 4.0
TA贡献1846条经验 获得超7个赞
您可以尝试使用 .shift 方法作为分母。这会将值降低 1。
在下面的示例中,发生的情况是
500 / NaN = NaN
415 / 500 = .83
293 / 415 = .71
...等等
df = df = pd.DataFrame({'value1':[500,415,293,126,115,140,90,190,217]})
# the first row will be NaN
# the first row of the df['value2'].shift() will be empty
# if you have a value for the first row you can fill it with .fillna(value for first row denomenator)
df['new_value'] = df['value1'] / df['value1'].shift() # .fillna(value of first denomenator)
df
添加回答
举报