我有一个元组列表,其中每个元组的长度相等,我需要将这些元组转换为Pandas数据帧,使dataframe的列等于元组的长度,并且每个元组项都是列之间的一个行条目。在
关于这个主题,我已经咨询过其他问题(例如,Convert a list of lists of tuples to pandas dataframe,List of list of tuples to pandas dataframe,split list of tuples in lists of list of tuples)都没有成功。在
我得到的最接近的是关于堆栈溢出的另一个问题的列表理解:
import pandas as pd
tupList = [[('commentID', 'commentText', 'date'), ('123456', 'blahblahblah', '2019')], [('45678', 'hello world', '2018'), ('0', 'text', '2017')]]
# Trying list comprehension from previous stack question:
pd.DataFrame([[y for y in x] for x in tupList])
但这会产生意想不到的结果:
^{pr2}$当预期结果如下:
0 1 2
0 commentID commentText date
1 123456 blahblahblah 2019
2 45678 hello world 2018
3 0 text 2017
总之:我需要的列等于每个元组的长度(在示例中为3),其中元组中的每个项是列之间的一个行条目。在
谢谢!在
只需将列表展平为元组列表(初始列表包含元组的子列表):
一个简短的代码:
编辑
您可以在
from_records
函数中直接进行列表理解。在输出
^{pr2}$相关问题 更多 >
编程相关推荐