8-Bit Borges
8-Bit Borges

Reputation: 10033

Pandas - get max row value if there's a zero and get mean value if there are no zeros

In this df:

      points_made  points_conceded 
0     0.00         30.00           
1     10.00        30.00    

How do I create a 'points_expected' column, where the column value is the max() row value if there is any 0.00, and the mean() on axis=0, if there are no 0.00, like so:

      points_made  points_conceded points_expected
0     0.00         30.00           30.00
1     10.00        30.00           20.00

Thanks.

Upvotes: 1

Views: 33

Answers (2)

Amin Ba
Amin Ba

Reputation: 2446

import pandas as pd
df = pd.DataFrame({
    'points_made': [0, 30],
    'points_conceded': [10, 30]
})

def func(row):
    if 0 in list(row):
        return max(row)
    else:
        return row.mean()

df['new'] = df.apply(lambda row: func(row), axis=1)
df

returns:

    points_made     points_conceded     new
0   0               10                  10.0
1   30              30                  30.0

Upvotes: 1

BENY
BENY

Reputation: 323316

Try replace with NaN

df['new'] = df.replace(0,np.nan).mean(1)
df
   points_made  points_conceded   new
0          0.0             30.0  30.0
1         10.0             30.0  20.0

Upvotes: 4

Related Questions