简体   繁体   中英

Taking average between two values in pandas Data frame

lets say that i have the following Dataframe,

A   B   C   D   E
0   1.625627    8.910396    9.171640    1.980580    8.429633
1   7.228290    6.431085    5.399684    8.442247    2.609367
2   NaN         NaN         NaN         NaN         NaN
3   2.533768    3.877104    8.199575    5.138173    7.248905
4   0.351828    1.233081    1.004183    6.497358    0.76487

and i want to iterate over each row to replace the NaN values to the average between the the upper value and the lower value.

i have tried using the following code but it did not result anything:

for i, row in df.iterrows():
    if i in row[:] > 1.0:
        print(i)

Use fillna() and shift() . shift(1) will give you upper value (as its shift the dataframe downward) and shift(-1) will give you lower value(as its shift the dataframe upword).

df = df.fillna((df.shift(1)+df.shift(-1))/2)

or

df.fillna((df.shift(1)+df.shift(-1))/2, inplace = True)

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