n0r*_*0ro 7 python tuples list-comprehension python-3.x pandas
我有一个元组列表列表,其中每个元组的长度都相等,我需要将元组转换为 Pandas 数据帧,使数据帧的列等于元组的长度,并且每个元组item 是跨列的行条目。
我已经咨询了有关此主题的其他问题(例如,将元组列表列表转换为熊猫数据框、将元组列表列表转换为熊猫数据框、将元组列表拆分为元组列表)未成功。
我得到的最接近的是来自 Stack Overflow 上不同问题的列表理解:
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])
Run Code Online (Sandbox Code Playgroud)
但这会产生意想不到的结果:
0 1
0 (commentID, commentText, date) (123456, blahblahblah, 2019)
1 (45678, hello world, 2018) (0, text, 2017)
Run Code Online (Sandbox Code Playgroud)
当预期结果如下:
0 1 2
0 commentID commentText date
1 123456 blahblahblah 2019
2 45678 hello world 2018
3 0 text 2017
Run Code Online (Sandbox Code Playgroud)
总而言之:我需要的列等于每个元组的长度(在示例中为 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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1278 次 |
| 最近记录: |