在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]:df2 Out[22]: 1 id2 name In[23]:df3=pd.DataFrame(df2.values.T,columns=df2.index) In[24]:df3 Out[24]: idname 02李四 In[25]:df1 Out[25]: idname 01张三 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'])
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。
评论(0)