简体   繁体   中英

Every time selecting present and last row data

I have a data frame like this: 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
. 
.

I want to create a new column C = A_pre - A_las /B_pre - B_las

A_pre = present sample A_las = last sample

For example,

Data of C at 08:30 = A(8:30)-A(8:15)/B(8:30)-B(8:15)

Data of C at 08:30 = (2446.80 - 368.93) /(402.07 - 400.45) = 1282.63

How to do it?

My solution:

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'])  

Output is:

# 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

My for loop function is successfully calculating. But I am unable to store each value in respective row. Instead, my function puts last calculated value (-145.48) in all rows. How to solve it?

Hope this can help:

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

To see the result:

print(df)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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