1

I have a pivot table that looks like this-

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

I want to reset the index to look like this-

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

Using reset_index with inplace=True does not work for me. Any suggestions?

mDe
  • 97
  • 1
  • 10

1 Answers1

2

You need remove [] in pivot or specify parameter values for prevent MultiIndex in columns:

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
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
  • Yet another dupe. Sir you taught me this answer long ago. – Bharath M Shetty Dec 21 '17 at 13:49
  • Yes, but find it is not easy for me, because to many answers :( – jezrael Dec 21 '17 at 13:49
  • 1
    In this case, the answer is talking about prevention rather than a cure... there may be a better question to close as a duplicate of, but for now this seems good enough to keep. – cs95 Dec 21 '17 at 13:52
  • @cᴏʟᴅsᴘᴇᴇᴅ - Can you reopen this question? – jezrael Dec 22 '17 at 10:16
  • The duplicate is applicable, but your answer is equally applicable if not more. In this case, it's okay for your answer to remain (in my opinion). If you disagree, you can reopen it. – cs95 Dec 22 '17 at 10:20