更改数据透视表的索引?

问题描述 投票:0回答:1

我有一个看起来像这样的数据透视表 -

        0
type    A    B   C
obs
x       NA   1   2
y       1    1   2
z       2    2   3

我想重置索引,看起来像这样 -

obs    A   B   C
x      NA  1   2
y      1   1   2
z      2   2   3

使用reset_indexinplace=True对我不起作用。有什么建议?

python pandas pivot-table
1个回答
1
投票

您需要在pivot中删除[]或指定参数values以防止列中的MultiIndex

df = pd.DataFrame({
'obs': ['x', 'x', 'y', 'y', 'y', 'z', 'z', 'z'], 
'type': ['B', 'C', 'A', 'B', 'C', 'A', 'B', 'C'], 
0: [1.0, 2.0, 1.0, 1.0, 2.0, 2.0, 2.0, 3.0]}
)
#print (df)


print (df.pivot_table(index='obs', columns='type'))
        0          
type    A    B    C
obs                
x     NaN  1.0  2.0
y     1.0  1.0  2.0
z     2.0  2.0  3.0

print (df.pivot_table(index='obs', columns='type', values=[0]))
        0          
type    A    B    C
obs                
x     NaN  1.0  2.0
y     1.0  1.0  2.0
z     2.0  2.0  3.0

print (df.pivot_table(index='obs', columns='type', values=0))

type    A    B    C
obs                
x     NaN  1.0  2.0
y     1.0  1.0  2.0
z     2.0  2.0  3.0
© www.soinside.com 2019 - 2024. All rights reserved.