Is it possible to create names with spaces and special characters when naming an aggregation column using pandas.NamedAgg
aggregation function? The typical syntax would be:
pvt = (df.groupby(by=[....])
.agg(value=pd.NamedAgg(column='col', aggfunc='count'))
)
But is there a way to create a column name that is not a valid python variable name (as value
in this example), but something like 'my new column name'
?
The only solution that I can think of now is to rename value
afterwards:
.rename(columns={'value': 'my new column name'})
If your column name does not make a valid Python variable name, you can use dictionary unpacking:
df.groupby(...).agg(**{
'My New Column Name': ('col_name', 'mean'),
'Column 42@#$': ('col_name', 'max')
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With