Created
September 21, 2023 17:45
-
-
Save anil-kk/07be579307882a1e1868dc61baa4355d to your computer and use it in GitHub Desktop.
pandas groupby apply multiple aggregation functions on dataframe columns
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import pandas as pd | |
import numpy as np | |
# Create a sample DataFrame | |
data = {'category': ['A', 'A', 'B', 'B', 'A', 'B'], | |
'value': [10, 20, 15, 25, 30, 35]} | |
df = pd.DataFrame(data) | |
# Group by 'category' and apply multiple aggregation functions | |
agg_functions = { | |
'value': [ | |
('_mean', 'mean'), | |
('_std', 'std'), | |
('_min', 'min'), | |
('_max', 'max'), | |
('_5th_percentile', lambda x: np.percentile(x, 5)), | |
('_95th_percentile', lambda x: np.percentile(x, 95)) | |
] | |
} | |
result_df = df.groupby('category').agg(agg_functions) | |
result_df.columns = [f'{column[0]}{column[1]}' for column in result_df.columns] | |
result_df = result_df.reset_index() | |
result_df |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment