Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/285.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在两个索引上使用多列将多行转换为单行_Python_Pandas - Fatal编程技术网

Python 在两个索引上使用多列将多行转换为单行

Python 在两个索引上使用多列将多行转换为单行,python,pandas,Python,Pandas,我正在尝试从以下内容转换熊猫数据帧: 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 致: 我有10种不同的可能类型和数千个ID,每个最多有10个版本 我试过: df.drop_

我正在尝试从以下内容转换熊猫数据帧:

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
致:

我有10种不同的可能类型和数千个ID,每个最多有10个版本

我试过:

df.drop_duplicates()
df.set_index(['ID','ID_VER','TYPE'])[['count','PRICE','DISCOUNT']].unstack()
但是得到错误:

索引包含重复的条目,无法重塑

虽然我试了很多,但我不明白为什么


谢谢你的帮助

熊猫正在为索引使用唯一值。你设置了一个三重索引,如果你这样做的话,看起来有些观测值会有相同的三个值。结果,
pandas
抛出了一个错误

   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
我可以复制您的错误,更改示例的一个值,使两个观察值具有相同的索引值:

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
ValueError:索引包含重复的条目,无法重塑


我想你想要这样的东西:

pd.pivot_table(your_df, values=['count', 'price', 'discount'], index=['ID','ID_ver'], columns='type')
如果要从多索引列展开:

your_df.columns = ['_'.join(col).strip() for col in your_df.columns.values]
要展平行多索引,请执行以下操作:

your_df = your_df.reset_index()

编辑:更改为pivot_表,添加了列展平、行展平

谢谢!考虑到尼古拉斯·热尔韦指出的问题,这是解决方案的一部分。
your_df = your_df.reset_index()