Milhouse
Milhouse

Reputation: 595

Find the average of the element above and below in that column if that element is 0 - Pandas DataFrame

I'd like to create a new dataframe using the same values from another dataframe, unless there is a 0 value. If there is a 0 value, I'd like to find the average of the entry before and after.

For Example:

df =  A  B  C
      5  2  1
      3  4  5
      2  1  0
      6  8  7

I'd like the result to look like the df below:

df_new = A  B  C
         5  2  1
         3  4  5
         2  1  6
         6  8  7

Upvotes: 0

Views: 165

Answers (1)

ranlot
ranlot

Reputation: 656

import pandas as pd
import numpy as np

df = pd.DataFrame({'A':[5, 3, 2, 6], 'B':[2, 4, 1, 8], 'C':[1, 5, 0, 7]})

Nrows = len(df)

def run(col):
        originalValues = list(df[col])
        values = list(np.where(np.array(list(df[col])) == 0)[0])
        indices2replace = filter(lambda x: x > 0 and x < Nrows, values)
        for index in indices2replace:
                originalValues[index] = 0.5 * (originalValues[index+1] + originalValues[index-1])
        return originalValues


newDF = pd.DataFrame(map(lambda x: run(x) , df.columns)).transpose()

Upvotes: 1

Related Questions