python - 将 pandas 系列转换为 DataFrame

标签 python pandas dataframe series

我有一个 Pandas 系列科幻小说:

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:

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]

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

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

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

构造 df 的方法有很多,请参阅docs

关于python - 将 pandas 系列转换为 DataFrame,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58060596/

相关文章:

python - Pandas TimerGrouper : Index with beginning

excel - 以多个名称保存一个 excel 文件

python-3.x - 使用分层抽样将 pandas Dataframe 分成 4 个部分

python - 基于条件循环将新行插入 Pandas DF

检查数据类字段是否具有默认值的 Pythonic 方法

python - Spyder: [Errno 2] 没有那个文件或目录

python - 如何告诉 Python unittest 使用函数中的自定义代码集退出

python Pandas : how to speed up exporting dataframes to csv?

pandas - 'NaTType' 对象没有属性 'days'

python - 如何在 pyspark 中将 Dataframe 转换为 RDD?