Pivot a pandas DataFrame to be the correct format: `DataError: No numeric types to aggregate`(将 pandas DataFrame 旋转为正确的格式:`DataError: No numeric types to aggregate`)
问题描述
这是我想要操作的 pandas DataFrame:
Here is a pandas DataFrame I would like to manipulate:
import pandas as pd
data = {"grouping": ["item1", "item1", "item1", "item2", "item2", "item2", "item2", ...],
"labels": ["A", "B", "C", "A", "B", "C", "D", ...],
"count": [5, 1, 8, 3, 731, 189, 9, ...]}
df = pd.DataFrame(data)
print(df)
>>> grouping labels count
0 item1 A 5
1 item1 B 1
2 item1 C 8
3 item2 A 3
4 item2 B 731
5 item2 C 189
6 item2 D 9
7 ... ... ....
我想将此数据框展开"为以下格式:
I would like to "unfold" this dataframe into the following format:
grouping A B C D
item1 5 1 8 3
item2 3 731 189 9
.... ........
如何做到这一点?我认为这会起作用:
How would one do this? I would think that this would work:
pd.pivot_table(df,index=["grouping", "labels"]
但我收到以下错误:
DataError: No numeric types to aggregate
推荐答案
有四种惯用的 pandas
方法可以做到这一点.
There are four idiomatic pandas
ways to do this.
- 分组列之间没有重复.不需要聚合
枢轴
set_index
数据透视表
分组方式
枢轴
df.pivot('grouping', 'labels', 'count')
set_index
df.set_index(['grouping', 'labels'])['count'].unstack()
pivot_table
df.pivot_table('count', 'grouping', 'labels')
groupby
df.groupby(['grouping', 'labels'])['count'].sum().unstack()
全部收益
labels A B C D grouping item1 5.0 1.0 8.0 NaN item2 3.0 731.0 189.0 9.0
时机
使用
groupby
、set_index
或pivot_table
方法,您可以使用fill_value=0轻松填充缺失值代码>
With the
groupby
,set_index
, orpivot_table
approach, you can easily fill in missing values withfill_value=0
df.pivot_table('count', 'grouping', 'labels', fill_value=0) df.groupby(['grouping', 'labels'])['count'].sum().unstack(fill_value=0) df.set_index(['grouping', 'labels'])['count'].sum().unstack(fill_value=0)
全部收益
labels A B C D grouping item1 5 1 8 0 item2 3 731 189 9
<小时>
关于
groupby
的其他想法因为我们不需要任何聚合.如果我们想使用
groupby
,我们可以通过使用影响较小的聚合器来最小化隐式聚合的影响.Because we don't require any aggregation. If we wanted to use
groupby
, we can minimize the impact of the implicit aggregation by utilizing a less impactful aggregator.df.groupby(['grouping', 'labels'])['count'].max().unstack()
或
df.groupby(['grouping', 'labels'])['count'].first().unstack()
定时
groupby
这篇关于将 pandas DataFrame 旋转为正确的格式:`DataError: No numeric types to aggregate`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将 pandas DataFrame 旋转为正确的格式:`DataError: No numeric types to aggregate`


基础教程推荐
- Python,确定字符串是否应转换为 Int 或 Float 2022-01-01
- matplotlib 设置 yaxis 标签大小 2022-01-01
- 在 Python 中将货币解析为数字 2022-01-01
- Kivy 使用 opencv.调整图像大小 2022-01-01
- Python 中是否有任何支持将长字符串转储为块文字或折叠块的 yaml 库? 2022-01-01
- 在 Django Admin 中使用内联 OneToOneField 2022-01-01
- 比较两个文本文件以找出差异并将它们输出到新的文本文件 2022-01-01
- 究竟什么是“容器"?在蟒蛇?(以及所有的 python 容器类型是什么?) 2022-01-01
- 对多索引数据帧的列进行排序 2022-01-01
- kivy 应用程序中的一个简单网页作为小部件 2022-01-01