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