每次选择当前和最后一行数据

时间:2019-03-16 15:09:08

标签: python python-3.x dataframe

我有一个这样的数据框:df =

                                  A                   B
2019-01-25 08:15:00         368.937200           400.459991
2019-01-25 08:30:00        2446.807365           402.070007
2019-01-25 08:45:00        2928.375786           387.779999
2019-01-25 09:00:00        3336.868420           381.529999
2019-01-25 09:15:00        3735.226080           387.850006
2019-01-25 09:30:00        4087.979328           374.839996
2019-01-25 09:45:00        4398.969370           389.359985
2019-01-25 10:00:00        4636.137977           380.589996
2019-01-25 10:15:00        4933.081631           370.429993
2019-01-25 10:30:00        5181.009806           363.619995
2019-01-25 10:45:00        5356.632156           362.459991
2019-01-25 11:00:00        5528.142683           386.869995
2019-01-25 11:15:00        5668.815429           363.470001
2019-01-25 11:30:00        5795.115442           355.839996
2019-01-25 11:45:00        5823.423663           373.55999
. 
.

我想创建一个新列C = A_pre-A_las / B_pre-B_las

A_pre =当前样本 A_las =最后一个样本

例如

C在08:30的数据= A(8:30)-A(8:15)/ B(8:30)-B(8:15)

C的08:30数据=(2446.80-368.93)/(402.07-400.45)= 1282.63

该怎么做?

我的解决方案:

for i in range(0,len(df.index)):
        x = 0
        x = ((df['A'].iloc[i]-df['A'].iloc[i-1])/
             (df['B'].iloc[i]-df['B'].iloc[i-1]))
        print(x)
        df['C'][i] = x
print(df['C'])  

输出为:

# Below is output of print(x)
-108.36672934277205 
1290.5898665696209 
-33.6996594301328 
-65.35882129611214
.
.
.
267.5508063249828
-59.56361658427877
-91.13780524775356
-15.836441236656086
38.48640472603791
-145.4802310927083

# Below is output of print(df['C'])
2019-01-25 08:15:00   -145.480231
2019-01-25 08:30:00   -145.480231
2019-01-25 08:45:00   -145.480231
2019-01-25 09:00:00   -145.480231
.
.
.
.
.
.
.
2019-03-08 09:00:00   -145.480231
2019-03-08 09:15:00   -145.480231
2019-03-08 09:30:00   -145.480231
2019-03-08 09:45:00   -145.480231

我的for循环函数正在成功计算。但是我无法将每个值存储在相应的行中。相反,我的函数将所有行的最后一个计算值(-145.48)放入。如何解决?

1 个答案:

答案 0 :(得分:0)

希望这可以帮助您

x = []
for i in range(0,len(df)):
    x.insert(len(x),(df.iloc[i][1]-df.iloc[i-1][1])/(df.iloc[i][2]-df.iloc[i-1][2]))
df["C"] = x

要查看结果:

print(df)