Skip to content

Instantly share code, notes, and snippets.

@jmquintana79
Last active January 20, 2025 08:02
Show Gist options
  • Save jmquintana79/90e8a897b3daa722a07fa8f239f81dd4 to your computer and use it in GitHub Desktop.
Save jmquintana79/90e8a897b3daa722a07fa8f239f81dd4 to your computer and use it in GitHub Desktop.
def create_agg_pivot_table_by_references(df:pd.DataFrame,
col_values:str,
col_var_ref_1:str,
col_var_ref_2:str,
sagg:str = 'median')->pd.DataFrame:
"""Create a pivot table by a given references and aggregator
Arguments:
df {pd.DataFrame} -- Data to be used.
col_values {str} -- Name of column values to be used.
col_var_ref_1 {str} -- Name of colomn to be used as first dimension.
col_var_ref_2 {str} -- Name of colomn to be used as second dimension.
Keyword Arguments:
sagg {str} -- Aggregator (default: {'median'})
Returns:
pd.DataFrame -- Pivot table.
"""
# validate arguments
assert isinstance(df, pd.DataFrame) and len(df) > 0
assert col_values in df.columns.tolist()
assert col_var_ref_1 in df.columns.tolist()
assert col_var_ref_2 in df.columns.tolist()
# pivot table
try:
# create pivot table and return
return pd.pivot_table(
df,
values=col_values,
index=col_var_ref_1,
columns=col_var_ref_2,
aggfunc=sagg,
fill_value=np.nan
)
except Exception:
raise ValueError("It was not possible to crete the pivot table.")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment