Python - 在pandas中计算列的前一行

时间:2018-04-06 11:23:21

标签: python 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

修改

我提到了这个Example示例,现在我得到输出为   代码:

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

1 个答案:

答案 0 :(得分:0)

代码:

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