好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

在Python中将pandas Series转换为DataFrame

我有一个熊猫系列sf:

email
email1@email测试数据    [1.0, 0.0, 0.0]
email2@email测试数据    [2.0, 0.0, 0.0]
email3@email测试数据    [1.0, 0.0, 0.0]
email4@email测试数据    [4.0, 0.0, 0.0]
email5@email测试数据    [1.0, 0.0, 3.0]
email6@email测试数据    [1.0, 5.0, 0.0]

我想将其转换为以下DataFrame:

index | email             | list
_____________________________________________
0     | email1@email测试数据  | [1.0, 0.0, 0.0]
1     | email2@email测试数据  | [2.0, 0.0, 0.0]
2     | email3@email测试数据  | [1.0, 0.0, 0.0]
3     | email4@email测试数据  | [4.0, 0.0, 0.0]
4     | email5@email测试数据  | [1.0, 0.0, 3.0]
5     | email6@email测试数据  | [1.0, 5.0, 0.0]

我找到了一种方法,但我怀疑它是更有效的方法:

df1 = pd.DataFrame(data=sf.index, columns=['email'])
df2 = pd.DataFrame(data=sf.values, columns=['list'])
df = pd.merge(df1, df2, left_index=True, right_index=True)
您可以使用DataFrame构造函数将这些作为params传递给dms,而不是创建2个临时dfs:

pd.DataFrame({'email':sf.index, 'list':sf.values})

有很多方法可以构建df,请参阅docs

查看更多关于在Python中将pandas Series转换为DataFrame的详细内容...

  阅读:26次