python - pandas 多行到单行,2 个索引上有多列
问题描述
我正在尝试从以下位置转换熊猫数据框:
ID ID_ver type count price discount
1 1 a 4 100 20
1 1 b 3 50 0
1 2 a 4 100 30
1 2 b 3 50 5
1 2 c 1 70 10
至:
ID ID_ver count_a price_a discount_a count_b price_b discount_b count_c price_c discount_c
我有 10 种不同的可能类型和数千个 ID,每个版本最多 10 个。
我试过了:
df.drop_duplicates()
df.set_index(['ID','ID_VER','TYPE'])[['count','PRICE','DISCOUNT']].unstack()
但得到错误:
索引包含重复条目,无法重塑。
尽我所能,不明白为什么。
谢谢你的帮助!
解决方案
pandas
正在为索引使用唯一值。您设置了三重索引,如果您这样做,似乎某些观察值将具有相同的三个值。结果,pandas
正在抛出错误。
我可以重现您更改示例的一个值的错误,以使两个观察值具有相同的索引值:
import pandas as pd
df = pd.read_clipboard()
df.iloc[2, 1] = 1
观察 0 和 2 现在具有相同的(未来)索引值,这将引发错误。
ID ID_ver type count price discount
0 1 1 a 4 100 20 # 1, 1, a
1 1 1 b 3 50 0
2 1 1 a 4 100 30 # 1, 1, a
3 1 2 b 3 50 5
4 1 2 c 1 70 10
df.set_index(['ID','ID_ver','type'])[['count','price','discount']].unstack()
ValueError:索引包含重复的条目,无法重塑
推荐阅读
- typescript - 将值绑定到 aurelia 中的日期字段
- html - Microsoft Office 渲染引擎不断强调锚标记(HTML 电子邮件)
- python - 如何使用 tkinter ttk 添加多项选择?
- vue.js - vue中页面刷新后如何显示加载的数据,数据显示在控制台而不显示在视图中
- google-sheets - 在一列中求和,直到它满足另一个类别
- r - 数据操作和数据透视
- docker - 错误:无法修补应用服务配置
- python - 将python中的绘图保存在两个不同的文件中
- android - 如何为相同语言但不同地区创建字符串资源?
- excel - workbook.close 崩溃 excel