Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to use column names with spaces in NamedAgg expressions?

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'})
like image 213
divingTobi Avatar asked Mar 03 '23 22:03

divingTobi


1 Answers

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')
})
like image 137
Code Different Avatar answered May 01 '23 03:05

Code Different