Skip to content Skip to sidebar Skip to footer

Assign New Value In Dataframe Column Based On Group Max

I have a data frame and I'd like to add a new column based the value in two columns, where one uses the group max. For example, here's an example DataFrame import pandas as pd impo

Solution 1:

You can return labels as a DataFrame with the same index as the group the function is being applied on.

def max_bal(df):
    max_row = df['col2'].max()
    labels = np.where((df['col3'] == 'yep') & 
                     (df['col2'] == max_row),
                     'Yes', 
                     'No')
    return pd.DataFrame(labels, index=df.index)

df['col4'] = df.groupby('col1').apply(max_bal)

Post a Comment for "Assign New Value In Dataframe Column Based On Group Max"