【问题标题】:Convert a list of lists of tuples to pandas dataframe将元组列表的列表转换为 pandas 数据框
【发布时间】:2017-06-06 14:54:27
【问题描述】:

我正在尝试将元组列表的列表转换为 pandas 数据框,但不知道该怎么做。我的地址结构如下:

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')]
]

理想情况下,我需要返回如下数据框:

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

到目前为止,我尝试的是旋转表格,但它没有产生预期的结果:

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

有没有人对我应该寻找实现理想数据框的方法有任何指导?

山姆

【问题讨论】:

  • 每条记录中似乎有两个房子。你想保留哪一个?

标签: python dataframe


【解决方案1】:

您可以将每条记录转换为字典,然后使用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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-22
    • 2017-06-22
    • 1970-01-01
    • 1970-01-01
    • 2020-12-13
    • 2017-03-12
    • 2021-11-14
    • 2021-08-11
    相关资源
    最近更新 更多