简体   繁体   中英

How can I make a pivot_table with categorical values?

I have four categorical columns In the following code.

Can I do a pivot with values (categorical column)?

 df.pivot_table(index=['DATE','COUNTRY'],columns='METRIC',values='VALUE',dropna=True).reset_index()

I have the next error:

DataError: No numeric types to aggregate

You should use the aggfunc parameter to define the aggregation function.

To get any value (if its unique for example) :

df.pivot_table(index=['DATE','COUNTRY'],columns='METRIC',values='VALUE',dropna=True, aggfunc='first').reset_index()

To concatenate all the strings :

df.pivot_table(index=['DATE','COUNTRY'],columns='METRIC',values='VALUE',dropna=True, aggfunc=lambda x: ', '.join(x)).reset_index()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM