Cheat Sheet for map, apply, applymap and groupby PANDAS

PHOTO EMBED

Fri Nov 18 2022 22:15:19 GMT+0000 (Coordinated Universal Time)

Saved by @janduplessis883 #pandas #groupby

## MAP (for Series)
series.map(function) 
Series.map({mapping dict})

#add a column to your df operating on each row
# Let's call this "custom_sum" as "sum" is a built-in function
def custom_sum(row):
    return row.sum()
df['D'] = df.apply(custom_sum, axis=1)

#add as row
df.loc['Row 5'] = df.apply(custom_sum, axis=0)

## APPLY (for DataFrame)
df.apply(lambda col: col.max(), axis = 0)     # default axis
df.apply(lambda row: row[‘A’] + row[‘B’], axis = 1)
df.applymap(my_funct_for_indiv_elements)
    df.applymap(lambda x: '%.2f' % x)

## GROUPBY
group = df.groupby('col_A')
group.mean()
group.apply(np.mean)
group.agg({
    col_A: ['mean', np.sum],
    col_B: my_custom_sum,
    col_B: lambda s: my_custom_sum(s)
    })

group.apply(custom_mean_function)
content_copyCOPY