将 Pandas 系列转换为 DataFrame [英] Convert pandas Series to DataFrame

查看:110
本文介绍了将 Pandas 系列转换为 DataFrame的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个熊猫系列科幻:

I have a Pandas series sf:

email
email1@email.com    [1.0, 0.0, 0.0]
email2@email.com    [2.0, 0.0, 0.0]
email3@email.com    [1.0, 0.0, 0.0]
email4@email.com    [4.0, 0.0, 0.0]
email5@email.com    [1.0, 0.0, 3.0]
email6@email.com    [1.0, 5.0, 0.0]

我想将其转换为以下 DataFrame:

And I would like to transform it to the following DataFrame:

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

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

I found a way to do it, but I doubt it's the more efficient one:

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 构造函数将它们作为 dict 中的参数传递,而不是创建 2 个临时 dfs:

Rather than create 2 temporary dfs you can just pass these as params within a dict using the DataFrame constructor:

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

构建 df 的方法有很多,参见 文档

There are lots of ways to construct a df, see the docs

这篇关于将 Pandas 系列转换为 DataFrame的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆