如何统计转换列转数据?
我有一个比较大的dfdate type2024-01-01 12024-01-01 22024-01-01 12024-01-02 32024-01-02 22024-01-02 32024-01-02 12024-01-02 12024-01-03 12024-01-03 42024-01-03 22024-01-03 5...
如何恰当地完成如下的统计转换date type1 type2 type3 type4 type52024-01-01 2 1 0 0 02024-01-02 2 1 2 0 02024-01-03 1 0 1 1 1...
谢谢高人指定。
回复
1个回答
test
2024-06-21
import pandas as pd
# 创建示例数据
data = {
'date': ['2024-01-01', '2024-01-01', '2024-01-01', '2024-01-02', '2024-01-02', '2024-01-02', '2024-01-02', '2024-01-02', '2024-01-03', '2024-01-03', '2024-01-03', '2024-01-03'],
'type': [1, 2, 1, 3, 2, 3, 1, 1, 1, 4, 2, 5]
}
df = pd.DataFrame(data)
df_dummies = pd.get_dummies(df, columns=['type'])
df_group = df_dummies.groupby("date").sum()
# 显示结果
print(df_dummies)
print("-" * 60)
print(df_group)
在pandas库中,get_dummies()
函数的作用是将分类变量转换为虚拟/指示变量,也称为one-hot编码。这个函数为每个唯一的类别值创建一个新的布尔列(只包含0和1),其中1表示原始数据中该类别的存在,0表示不存在。这里面先使用 get_dummies()
函数将你原先的数据生成一个虚拟列。
然后再通过 groupby
和 sum
函数再分别分组和求和,求和可以用 sum
也可以用 aggregate('sum')
,然后就有了下面的结果。
输出结果:
date type_1 type_2 type_3 type_4 type_5
0 2024-01-01 1 0 0 0 0
1 2024-01-01 0 1 0 0 0
2 2024-01-01 1 0 0 0 0
3 2024-01-02 0 0 1 0 0
4 2024-01-02 0 1 0 0 0
5 2024-01-02 0 0 1 0 0
6 2024-01-02 1 0 0 0 0
7 2024-01-02 1 0 0 0 0
8 2024-01-03 1 0 0 0 0
9 2024-01-03 0 0 0 1 0
10 2024-01-03 0 1 0 0 0
11 2024-01-03 0 0 0 0 1
------------------------------------------------------------
type_1 type_2 type_3 type_4 type_5
date
2024-01-01 2 1 0 0 0
2024-01-02 2 1 2 0 0
2024-01-03 1 1 0 1 1
回复
适合作为回答的
- 经过验证的有效解决办法
- 自己的经验指引,对解决问题有帮助
- 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
- 询问内容细节或回复楼层
- 与题目无关的内容
- “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容