我有一个这样的列表“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)
但这不是我想要的
预期结果:
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/