蟒蛇,将大 pandas 系列转换为大 pandas 数据框的最佳方式 [英] python, best way to convert a pandas series into a pandas dataframe

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

问题描述

我有一个熊猫系列sf:

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)


推荐答案

而不是创建2个临时dfs,您可以使用DataFrame构造函数:

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,请参阅 docs

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

这篇关于蟒蛇,将大 pandas 系列转换为大 pandas 数据框的最佳方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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