j_alnoktha
j_alnoktha

Reputation: 21

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)

Upvotes: 2

Views: 660

Answers (1)

Hamza usman ghani
Hamza usman ghani

Reputation: 2243

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)

Upvotes: 3

Related Questions