如何使用分类值创建pivot_table?

问题描述 投票:0回答:1

我在以下代码中有四个分类列。

我可以使用值(分类列)进行转轴吗?

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

我有下一个错误:

DataError: No numeric types to aggregate
python python-3.x pandas pivot-table melt
1个回答
1
投票

您应该使用aggfunc参数来定义聚合函数。

获取任何值(例如,如果它是唯一的):

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

要连接所有字符串:

df.pivot_table(index=['DATE','COUNTRY'],columns='METRIC',values='VALUE',dropna=True, aggfunc=lambda x: ', '.join(x)).reset_index()
© www.soinside.com 2019 - 2024. All rights reserved.