繁体   English   中英

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

[英]Every time selecting present and last row data

我有一个这样的数据框: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)放在所有行中。 怎么解决?

希望这可以帮助:

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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM