我有一个数据框架,我真的很难将其转换为正确的结构,我想在这里寻求一些帮助,因为我无法找出要使用的正确索引、列和值参数。我正在使用python。
我有这个数据框(抱歉它很长,但我觉得有必要包括所有内容来显示结构):
Size Color Parameter Estimate
---------------------------------------------
Small Blue P1 XX
Small Blue P2 XX
Small Blue P3 XX
Small Red P1 XX
Small Red P2 XX
Small Red P3 XX
Small Green P1 XX
Small Green P2 XX
Small Green P3 XX
Medium Blue P1 XX
Medium Blue P2 XX
Medium Blue P3 XX
Medium Red P1 XX
Medium Red P2 XX
Medium Red P3 XX
Medium Green P1 XX
Medium Green P2 XX
Medium Green P3 XX
Big Blue P1 XX
Big Blue P2 XX
Big Blue P3 XX
Big Red P1 XX
Big Red P2 XX
Big Red P3 XX
Big Green P1 XX
Big Green P2 XX
Big Green P3 XX
我想把这个数据框变成这样:
P1 P2 P3
Blue Green Red Blue Green Red Blue Green Red
Big 34 17 12 19 39 28 49 39 48
Medium 40 15 24 15 29 21 41 12 26
Small 10 31 19 46 39 43 16 13 41
我尝试使用pd.pivot()
和pd.pivot_table()
,运行许多组合:
df.pivot(index ='Size', columns ='Color', values =['Parameter', 'Estimate'])
但是每次我都得到这个错误:
ValueError: Index contains duplicate entries, cannot reshape
如何正确填写数据透视表参数,以便将初始数据框重构为目标数据框?
在columns
参数中需要['Parameter', 'Color']
:
(df.pivot(index='Size', columns=['Parameter', 'Color'], values='Estimate')
.sort_index(axis=1))
Parameter P1 P2 P3
Color Blue Green Red Blue Green Red Blue Green Red
Size
Big XX XX XX XX XX XX XX XX XX
Medium XX XX XX XX XX XX XX XX XX
Small XX XX XX XX XX XX XX XX XX
可能您的实际数据有重复的索引(未显示在示例数据中),这意味着您需要用groupby
和cumcount
ed列消除歧义,然后您的index
参数将成为['Size', 'cumcounted_column']
的列表。