python中series转dataframe的两种方法

2023-12-14 11:40:21网络知识悟空

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

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培训机构:筋斗云。

发表评论: