0

I have a table with a structure is like:

[["A","1","12"],
["A","2","112"],
["B","0","121"],
["B","1","21"],
["B","2","51"]]

I need to change it into a dataframe like:

   0  1  2
A  0  12 112
B 121 21 51

I tried the stack function, but it doesn't seem to have worked.

iz_
  • 15,923
  • 3
  • 25
  • 40
Xin Yang
  • 3
  • 1
  • Please [edit] to add meaningful code and a problem description here. Posting a [Minimal, Complete, Verifiable Example](http://$SITEURL$/help/mcve) that demonstrates your problem would help you get better answers. Thanks! – SivolcC Feb 11 '19 at 00:43

1 Answers1

1

You can use pivot():

df = pd.DataFrame(data).pivot(index=0, columns=1, values=2)
df

1    0   1    2
0              
A  NaN  12  112
B  121  21   51

If you need to be cosmetically precise, use fillna() and rename_axis():

df.fillna(0).rename_axis(None, axis="index").rename_axis(None, axis="columns")

df
     0   1    2
A    0  12  112
B  121  21   51

Data:

data = [["A","1","12"],
        ["A","2","112"],
        ["B","0","121"],
        ["B","1","21"],
        ["B","2","51"]]
andrew_reece
  • 20,390
  • 3
  • 33
  • 58
  • 1
    `df = pd.DataFrame(data).pivot(0,1,2).rename_axis(index=None, columns=None)` Pandas version >0.24.0 – Alex Feb 11 '19 at 01:03