在python的pandas包中,其中一个数据类型Dataframe想要转换为Serie会自动转换,那将Series转为Dataframe又如何实现呢?本文介绍python中series转dataframe的两种方法:1、使用to_frame()后,再转置index与columns实现Series转换成Dataframe;2、先to_dict()转成字典再转为list再转dataframe。
方法一:使用to_frame()后,再转置index与columns实现Series转换成Dataframe
In[21]:df2=df1.loc[1].to_frame()In[22]:df2Out[22]:1id2nameIn[23]:df3=pd.Dataframe(df2.values.T,columns=df2.index)In[24]:df3Out[24]:idname02李四In[25]:df1Out[25]:idname01张三12李四23王五
方法二:先to_dict()转成字典再转为list再转dataframe
fori,jindf.iterrows():j=pd.Dataframe([j.to_dict()])#series有转framedict等方法print(j)print(type(j))print(j['age'])