![](/img/trans.png)
[英]Python - Simliar to excel formula how to do the calculation for each rows in python/pandas by referring to previous row
[英]Python - Referring previous row in the calculation of a column in pandas
我正在嘗試使用上一行的列值(也是計算字段)來派生計算字段。
輸入數據聲望:
0 1 2 3 4 5
0 94000.0 9.970228 -21.062708 0.0 0.0 0.0
1 0.0 9.970228 -20.748142 0.0 0.0 0.0
要求的輸出:
0 1 2 3 4 5 d
0 94000.0 9.970228 -21.062708 0.0 0.0 0.0 9428.06934
1 0.0 9.970228 -20.748142 0.0 0.0 0.0 9407.00663
碼:
df= pd.DataFrame([(94000, 9.9702279, -21.0627081029071, 0, 0, 0),
(0, 10.1213880586432, -20.7481423282323, 0, 0, 0)])
df['d'] = (df[0]/df[1]).fillna(0) + ((df[0]/df[1]).shift(1) + d[2].shift(1)).fillna(0) +
df[3].shift(1).fillna(0) + df[4].shift(1) + df[5].shift(1)
我得到的輸出:
0 1 2 3 4 5 d
0 94000.0 9.970228 -21.062708 0.0 0.0 0.0 9428.06934
1 0.0 9.970228 -20.748142 0.0 0.0 0.0 -20.748142
編輯:
我參考了這個示例示例,現在我得到的輸出為代碼:
df.loc[0, 'd'] = df.loc[0, 5]
for i in range(1, len(df)):
df.loc[i, 'd'] = (df.loc[i, 0] / df.loc[i, 1]) + (df.loc[i-1, 0] / df.loc[i-1, 1]) + df.loc[i-1, 2]
0 1 2 3 4 5 d
0 94000 9.970228 -21.062708 0 0 0 0.000000
1 0 10.121388 -20.748142 0 0 0 9407.006634
碼:
import pandas as pd
df = pd.DataFrame([(94000, 9.9702279, -21.0627081029071, 0, 0, 0),
(0, 10.1213880586432, -20.7481423282323, 0, 0, 0),
(0, 9.6525370469631300, -21.7559382552248, 0, 0, 0)])
df.loc[0, 'd'] = df.loc[0, 5]
for i in range(0, len(df)):
if i ==0:
df.loc[i, 'd'] = (df.loc[i, 0] / df.loc[i, 1])
else:
df.loc[i, 'd'] = (df.loc[i - 1, 'd']) + df.loc[i - 1, 2]
print(df)
輸出:
0 1 2 3 4 5 d
0 94000 9.970228 -21.062708 0 0 0 9428.069342
1 0 10.121388 -20.748142 0 0 0 9407.006634
2 0 9.652537 -21.755938 0 0 0 9386.258492
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.