当前位置:   article > 正文

python把dataframe转置_python中series转dataframe的两种方法

python dataframe转置

792116d4496f87b04305a8142b57bbd6.png

在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转换成DataFrameIn [21]: df2 = df1.loc[1].to_frame()

In [22]: df2

Out[22]:

1

id     2

name

In [23]: df3 = pd.DataFrame(df2.values.T,columns=df2.index)

In [24]: df3

Out[24]:

id name

0  2   李四

In [25]: df1

Out[25]:

id name

0  1   张三

1  2   李四

2  3   王五

方法二:先to_dict()转成字典再转为list再转dataframefor i ,j in df.iterrows():

j=pd.DataFrame([j.to_dict()]) #series有转frame dict等方法

print(j)

print(type(j))

print(j['age'])

以上就是python中series转dataframe的两种方法,希望能对你有所帮助哟·更多python学习推荐:python教程。

本文内容由网友自发贡献,转载请注明出处:https://www.wpsshop.cn/w/凡人多烦事01/article/detail/403152
推荐阅读
相关标签
  

闽ICP备14008679号