Python列表转换成Dict到Dataframe的列表

问题描述 投票:0回答:3

将大量的列表转换成字典和代码仅适用于列表列表中的第一项。

a_list = [[('Bedrooms', ' 4'),
  ('Street Address', ' 90 Lake '),
  ('Contact Phone', ' 970-xxx-xxxx'),
  ('Bathrooms', ' 5'),
  ('Price', ' $5,350,000'),
  ('Zip Code', ' 5000')],

  [('Bedrooms', ' 4'),
  ('Street Address', ' 1490 Creek '),
  ('Contact Phone', ' 970-xxx-xxx3'),
  ('Bathrooms', ' 10'),
  ('Price', ' $7,350,000'),
  ('Zip Code', ' 6000'),
  ('City', ' Edwards'),
  ('Price1', ' 4200000')],

[('Street Address', ' 280 Lane'),
  ('Bedrooms', ' 2'),
  ('Property Type', ' Townhouse'),
  ('Square Feet', ' 3000'),
  ('Bathrooms', ' 4'),
  ('Contact Phone', ' 303-xxx-xxxx'),
  ('MLS', ' 66666'),
  ('Contact Name', ' C Name'),
  ('Brokerage', ' Real Estate'),
  ('City', 'Creek'),
  ('Zip Code', '89899'),
  ('Price1', ' 2100000'),
  ('Posted On', ' Nov 13, 2019')
]]

当前代码仅将k,v分配给第一项:

items = {}
for line in list:
    for i in range(len(line)):
        key = line[i][0]
        value = line[i][1]
        items[key] = value
        items.update(line)

结果:

items = {'Bedrooms':' 4'),
  ('Street Address': ' 90 Lake '),
  ('Contact Phone': ' 970-xxx-xxxx'),
  ('Bathrooms': ' 5'),
  ('Price': ' $5,350,000'),
  ('Zip Code': ' 5000'}

最终,我想从列表列表中构建与之匹配的DataFrame键和值。

python pandas dictionary nested-lists
3个回答
2
投票

通过使用map将每个列表转换为字典,然后在其上调用DataFrame构造函数,是一种更好的方法。另外,在这种情况下,请勿将内置函数用作变量名list。我继续将您的输入数据重命名为变量data

dicts = list(map(dict, data))
pd.DataFrame(dicts)

  Bathrooms Bedrooms     Brokerage   ...    Square Feet Street Address Zip Code
0         5        4           NaN   ...            NaN       90 Lake      5000
1        10        4           NaN   ...            NaN    1490 Creek      6000
2         4        2   Real Estate   ...           3000       280 Lane    89899

[3 rows x 14 columns]

0
投票

这样的事情?

unpacked = [{k: v for k,v in one_list} for one_list in list_of_lists]
pd.DataFrame(unpacked)

0
投票

Python中的字典是一种存储键-值对的数据结构。本质上,每当您向字典中添加键值对(使用更新)时,都需要一个唯一的键。它执行以下操作:

  1. 检查密钥是否存在
  2. 如果存在密钥,它将值更新为新值
  3. 如果它们的键不存在,则将键值对添加到字典中

您可以查看此链接以更好地了解'update'

https://python-reference.readthedocs.io/en/latest/docs/dict/update.html

尽管有更简便的方法,但是代码的问题是最后一行,即

items.update(line)

代替您的代码,您可以使用下面的代码(如果选择继续使用相同的方法,而不是其他答案所建议的方法):

items = {}
new_list = [] # another list
for line in list:
    for i in range(len(line)):
        key = line[i][0]
        value = line[i][1]
        items[key] = value
    new_list.append(items) # use this line instead of your update

然后

import pandas as pd
pd.DataFrame(new_list)

这应该给您您想要的结果。

© www.soinside.com 2019 - 2024. All rights reserved.