python - 如何将列表转换为具有多列的数据框?

标签 python pandas list dataframe

我有一个这样的列表“result1”:

[[("tt0241527-Harry Potter and the Philosopher's Stone", 1.0),
  ('tt0330373-Harry Potter and the Goblet of Fire', 0.9699),
  ('tt1843230-Once Upon a Time', 0.9384),
  ('tt0485601-The Secret of Kells', 0.9347)]]

我想把它转换成三列数据框,我试过了:

pd.DataFrame(result1)

但这不是我想要的

enter image description here

预期结果:

    Number             Title                          Value
 tt0241527  Harry Potter and the Philosopher's Stone   1.0
 tt0330373  Harry Potter and the Goblet of Fire       0.9699

最佳答案

您可以尝试重新定义您的输入:

[elt1.split('-') + [elt2] for elt1, elt2 in result1[0] ]

完整示例:

result1 = [[("tt0241527-Harry Potter and the Philosopher's Stone", 1.0),
  ('tt0330373-Harry Potter and the Goblet of Fire', 0.9699),
  ('tt1843230-Once Upon a Time', 0.9384),
  ('tt0485601-The Secret of Kells', 0.9347)]]
# Columns name in dataframe
columns_name = ["Number", "Title", "Value"]

data = [elt1.split('-') + [elt2] for elt1, elt2 in result1[0] ]
print(data)
# [['tt0241527', "Harry Potter and the Philosopher's Stone", 1.0], 
#  ['tt0330373', 'Harry Potter and the Goblet of Fire', 0.9699],
#  ['tt1843230', 'Once Upon a Time', 0.9384],
#  ['tt0485601', 'The Secret of Kells', 0.9347]]

df = pd.DataFrame(data, columns=columns_name)
print(df)
#       Number                                     Title   Value 
# 0  tt0241527  Harry Potter and the Philosopher's Stone  1.0000
# 1  tt0330373       Harry Potter and the Goblet of Fire  0.9699
# 2  tt1843230                          Once Upon a Time  0.9384
# 3  tt0485601                       The Secret of Kells  0.9347

关于python - 如何将列表转换为具有多列的数据框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57468278/

相关文章:

python - 从 ipython 捕获库 f2py 调用 stdout

python - 如何向 df 添加一列以对 A 列中条目的所有匹配值求和?

python - 将 pandas DataFrame 写入包含一些空行的 csv 文件

python - 根据条件 pandas 数据框列删除字符串

python绝对XPath返回空列表,通用查询更好吗?

python - 如何以最简单的方式获取以下字典?

python - 我怎样才能停止Python中的循环迭代

javascript - channel Google App Engine Channel.open() 不起作用

具有用于数据库访问的 API 的 Python 应用程序

python - 使用列表位置中包含的项目进行计算(遗传算法适合度)