Is df.mean(axis=1) function dataframe python for all row?

María Marcela Pérez Jiménez :

In the next code, I want, when in a row value of 0.254 is found, it is not averaged, the value 0.254 is left and it goes to the next row, but it does not work, it averages all the values

df = pd.DataFrame({'uno': [1, 2, 3], 'dos': [0.254, 5, 6], 'tres': [7, 8, 9]}, index=['x', 'y', 'z'])

df_range = len(df)
for row in df:
    if df[row][i]==0.254:
        df['mean'][i]=0.254
    else:
        df['mean'] = df.mean(axis=1)
print df

Do you know where it could be wrong? Maybe in the part:

 else:
            df['mean'] = df.mean(axis=1)

But I don't know how to fix it

Thanks!

Jon Clements :

Use np.where to set the mean to 0.254 if any value in that row is 0.254 otherwise set it to the mean of the row itself, eg:

df['mean'] = np.where(df.eq(0.254).any(axis=1), 0.254, df.mean(axis=1))

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=410671&siteId=1