Pandas数据帧元组列表?

2024-09-29 16:18:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个元组列表,其中每个元组的长度相等,我需要将这些元组转换为Pandas数据帧,使dataframe的列等于元组的长度,并且每个元组项都是列之间的一个行条目。在

关于这个主题,我已经咨询过其他问题(例如,Convert a list of lists of tuples to pandas dataframeList of list of tuples to pandas dataframesplit 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),其中元组中的每个项是列之间的一个行条目。在

谢谢!在


Tags: oftoindataframepandas列表条目lists
3条回答

只需将列表展平为元组列表(初始列表包含元组的子列表):

In [1251]: tupList = [[('commentID', 'commentText', 'date'), ('123456', 'blahblahblah', '2019')], [('45678', 'hello world', '2018'), ('0', 'text', '2017')]]

In [1252]: pd.DataFrame([t for lst in tupList for t in lst])
Out[1252]: 
           0             1     2
0  commentID   commentText  date
1     123456  blahblahblah  2019
2      45678   hello world  2018
3          0          text  2017

一个简短的代码:

from itertools import chain
import pandas as pd

tupList = [[('commentID', 'commentText', 'date'), ('123456', 'blahblahblah', '2019')], [('45678', 'hello world', '2018'), ('0', 'text', '2017')]]

new_list = [x for x in chain.from_iterable(tupList)]
df = pd.DataFrame.from_records(new_list)

编辑

您可以在from_records函数中直接进行列表理解。在

tupList = [[('commentID', 'commentText', 'date'), ('123456', 'blahblahblah', '2019')], [('45678', 'hello world', '2018'), ('0', 'text', '2017')]]
print(pd.DataFrame(sum(tupList,[])))

输出

^{pr2}$

相关问题 更多 >

    热门问题