[英]how I divide df['2'] by df['1'] throughout a whole column in a dataframe?
I'm trying to find the change in nav in my dataframe by dividing each index by the previous index.我试图通过将每个索引除以前一个索引来查找数据帧中导航的变化。 I'm new to this and am stumped!
我是新手,很难过! Hope you can help.
希望你能帮忙。 Thanks!
谢谢!
t1 = 0
d = []
for f in final_df['nav']:
t = float(f)
d.append(t / t1)
t1 = t
print(d)
You can try using the .shift method for the denominator.您可以尝试使用 .shift 方法作为分母。 This will move the values down by one.
这会将值向下移动一。
In the example below what happens is在下面的例子中会发生什么
500 / NaN = NaN 500 / NaN = NaN
415 / 500 = .83 415 / 500 = .83
293 / 415 = .71 293 / 415 = .71
... and so forth ……等等
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
Try divided by shift尝试除以班次
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
您不需要为此实现循环函数,使用pandas pct_change
函数
df['nav'].pct_change()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.