我不确定这些数据是否正确采用宽格式,但我想做的是以下内容:
从d1
形状转换为d2
形状
In [26]: d1 = pd.DataFrame({'where':['x','y'],
...: 'p1':[3,7],
...: 'p2':[11,12]})
In [27]: d2=pd.DataFrame({
...: 'where':['x','x','y','y'],
...: 'who':['p1','p2','p1','p2'],
...: 'value':[3,11,7,12]})
看起来像:
In [10]: d1
Out[10]:
where p1 p2
0 x 3 11
1 y 7 12
In [11]: d2
Out[11]:
where who value
0 x p1 3
1 x p2 11
2 y p1 7
3 y p2 12
我认为这是某种形式的d1.pivot( ... )
,但我似乎不知道如何去做。
因此,需要明确的是,我希望能够使用 pandas 将数据 d1
reshape 为 d2
的结构。
编辑
以下方法可行,但这是一个很糟糕的方法
d3 = d1.pivot(columns='where').T.reset_index()
d3.columns = ['who','where','a','b']
d3 = d3.loc[:,['where','who','a','b']]
d3 = d3.sort_values('where')
d3.fillna(value=0,inplace=True)
d3['c'] = d3.a + d3.b
d3.drop(['a','b'],axis=1,inplace=True)
d3.columns=['where','who','value']
In [43]: d3
Out[43]:
where who value
0 x p1 3.0
2 x p2 11.0
1 y p1 7.0
3 y p2 12.0
编辑2
以下作品
In [49]: d1.melt(id_vars='where')
Out[49]:
where variable value
0 x p1 3
1 y p1 7
2 x p2 11
3 y p2 12
我很好奇这是否可以用pivot实现?我的印象是所有这些操作都可以使用数据透视函数来完成
编辑 3 - 恢复原始结构的示例
上面我指的是pivot
函数,而不是pivot_table
函数,尽管下面的示例是在给定最终值的情况下查找原始结构的方法
d1.melt(id_vars='where').pivot_table(values="value", index="where", columns="variable")
variable p1 p2
where
x 3 11
y 7 12
最佳答案
不,这不能用数据透视表来完成。您没有在数据框中旋转值。
您可以使用pivot将d2返回到d1。例如,下面显示 d1 变成 d2(按照最初的要求),然后我们可以使用pivot_table 将 d2 返回到 d1。
d1.melt(id_vars='where')
where variable value
0 x p1 3
1 y p1 7
2 x p2 11
3 y p2 12
d1.melt(id_vars='where').pivot(values="value", index="where", columns="variable")
variable p1 p2
where
x 3 11
y 7 12
您想要做的是将数据从宽数据集“逆透视”到长数据集
关于python - 将 pandas 数据框从宽转为长,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59988979/