Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.6k views
in Technique[技术] by (71.8m points)

pandas 字典转换成dataFrame,如何将索引放在第一行

数据

res = {
    0:{'age':18,'name':'zhangsan'},
 1:{'age':24,'name':'lisi'},
}
df = pd.DataFrame(res)

结果

             0     1
age         18    24
name  zhangsan  lisi

字典key 很多的情况下 如何不用set_indexs手动设置索引,把结果变成下面的,不能再初始化dataframe的时候设置,因为key字典的key很多。

    age  name
0   18   zhangsan    
1   24   lisi

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

只需要转置一下就可以达到你要的效果

df = pd.DataFrame(res).T
df
    age    name
0    18    zhangsan
1    24    lisi

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...