1987WEB视界-分享互联网热点话题和事件

您现在的位置是:首页 > WEB开发 > 正文

WEB开发

python中series转dataframe的两种方法

1987web2024-03-25WEB开发32

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