我有一个表,其结构类似于:
[["A","1","12"],
["A","2","112"],
["B","0","121"],
["B","1","21"],
["B","2","51"]]
我需要将其更改为如下数据框:
0 1 2
A 0 12 112
B 121 21 51
我尝试了栈功能,但是似乎没有用。
答案 0 :(得分:1)
您可以使用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
如果需要精确修饰,请使用fillna()
和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 = [["A","1","12"],
["A","2","112"],
["B","0","121"],
["B","1","21"],
["B","2","51"]]