简体   繁体   English

将元组列表列表转换为Pandas DataFrame

[英]Convert a list of lists of tuples to pandas dataframe

I'm trying to transform a list of lists of tuples to a pandas dataframe but can't figure out how to do so. 我正在尝试将元组列表的列表转换为pandas数据框,但不知道该怎么做。 My addresses are structured like so: 我的地址结构如下:

addresses = [
 [('the vicars inn', 'house'), ('68', 'house_number'), ('church lane', 'road'), ('arlesey', 'city'), ('beds', 'house')],
 [('the old oak', 'house'), ('85', 'house_number'), ('church lane', 'road'), ('arlesey', 'city'), ('beds', 'house')],
 [('adj', 'road'), ('85', 'house_number'), ('high street', 'road'), ('arlesey', 'city'), ('beds', 'house')],
 [('arlesey community centre', 'house'), ('high street', 'road'), ('arlesey', 'city'), ('beds', 'house')],
 [('arlesey community centre', 'house'), ('high street', 'road'), ('arlesey', 'city'), ('beds', 'house')]
]

Ideally, I need to return a dataframe like: 理想情况下,我需要返回如下数据框:

      city           house             house_number       road
0     arlesey        the vicars inn    68                 church lane
1     arlesey        the old oak       85                 church lane

What I've tried so far is to pivot the table but it is not producing the intended outcome: 到目前为止,我已经尝试过旋转表,但是并没有产生预期的结果:

pd.DataFrame.from_records(addresses[0]).pivot(columns=1, values=0)

Does anyone have any guidance on methods I should be looking at to achieve my ideal dataframe? 有人对实现理想数据框应使用的方法有任何指导吗?

Sam 山姆

You can convert each record to a dictionary and then use DataFrame.from_records : 您可以将每个记录转换为字典,然后使用DataFrame.from_records

pd.DataFrame.from_records([{k: v for v, k in row} for row in addresses])

#      city house   house_number    road
#0  arlesey beds              68    church lane
#1  arlesey beds              85    church lane
#2  arlesey beds              85    high street
#3  arlesey beds             NaN    high street
#4  arlesey beds             NaN    high street

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM