百科狗-知识改变命运!

python中series转dataframe的两种方法

是丫丫呀2年前 (2023-11-19)阅读数 34#技术干货
文章标签方法

python中series转dataframe的两种方法

在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张三

python中series转dataframe的两种方法

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'])

以上就是python中series转dataframe的两种方法,希望能对你有所帮助哟·更多Python学习教程请关注IT培训机构:开发教育。

内容声明:本文中引用的各种信息及资料(包括但不限于文字、数据、图表及超链接等)均来源于该信息及资料的相关主体(包括但不限于公司、媒体、协会等机构)的官方网站或公开发表的信息。部分内容参考包括:(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供参考使用,不准确地方联系删除处理!本站为非盈利性质站点,本着为中国教育事业出一份力,发布内容不收取任何费用也不接任何广告!)
{if $zbp->Config('yd1125')->foot}