如何解开嵌套词典,其中不是每个顶级键都具有所有第二级键?
我从网站上搜集了有关物业的数据。该网站为每个属性最多提供7个属性,但是属性类型在属性之间有所不同(即“土地”属性类型不显示“建筑物大小”作为属性,因为没有建筑物)。
作为解决此问题的第一步,我将属性类型和值都抓取为单独的列,并将数据转换为字典形式,其中每个属性都有唯一的ID_Number和一系列key:value对。现在,我想将该字典解压缩到一个数据帧中,其中列标题将代表所有可能的第二级键(属性类型),而列值将是与属性键关联的“值”。
数据示例如下所示:
{1: [{'Status:': 'For Lease',
'Price:': '$3.17 SF/Mo',
'Property Type:': 'Retail',
'Sub-Type:': 'Office, Retail',
'Spaces:': '2 Spaces',
'Space Available:': '0.00 - 0.03 AC',
'Building Size:': '9,161 SF'}],
2: [{'Status:': 'For Lease',
'Price:': '$1.25 SF/Mo',
'Property Type:': 'Office',
'Sub-Type:': 'Office',
'Spaces:': '1 Space',
'Space Available:': '0.03 AC',
'Building Size:': '11,332 SF'}],
3: [{'Status:': 'For Sale',
'Price:': 2521740,
'Property Type:': 'Retail',
'Sub-Type:': 'Fast Food',
'Building Size:': '2,410 SF',
'Cap Rate:': 0.0575,
'Lot Size:': '76,666 SF'}],
4: [{'Status:': 'For Lease',
'Price:': '$0.63 SF/Mo',
'Property Type:': 'Retail',
'Sub-Type:': 'Retail',
'Spaces:': '1 Space',
'Space Available:': '0.50 AC',
'Building Size:': '59,095 SF'}],
我将如何提取它?我在from_dict上尝试了几种变体,但是还没有找到可行的解决方案。
提前感谢!
您可以通过几种方法来执行此操作。我不是熊猫专家,所以可能会有更优雅的解决方案。但是,这是我快速而又肮脏的方法(顺便说一句,您提供的示例数据中有9个唯一属性,而不是7个):
import pandas as pd
data = {1: [{'Building Size:': '9,161 SF',
'Price:': '$3.17 SF/Mo',
'Property Type:': 'Retail',
'Space Available:': '0.00 - 0.03 AC',
'Spaces:': '2 Spaces',
'Status:': 'For Lease',
'Sub-Type:': 'Office, Retail'}],
2: [{'Building Size:': '11,332 SF',
'Price:': '$1.25 SF/Mo',
'Property Type:': 'Office',
'Space Available:': '0.03 AC',
'Spaces:': '1 Space',
'Status:': 'For Lease',
'Sub-Type:': 'Office'}],
3: [{'Building Size:': '2,410 SF',
'Cap Rate:': 0.0575,
'Lot Size:': '76,666 SF',
'Price:': 2521740,
'Property Type:': 'Retail',
'Status:': 'For Sale',
'Sub-Type:': 'Fast Food'}],
4: [{'Building Size:': '59,095 SF',
'Price:': '$0.63 SF/Mo',
'Property Type:': 'Retail',
'Space Available:': '0.50 AC',
'Spaces:': '1 Space',
'Status:': 'For Lease',
'Sub-Type:': 'Retail'}],
}
df = pd.DataFrame()
for property_num, property_list in data.items():
for property_dict in property_list: # you only have one per list, so this isn't really needed
df = df.append(property_dict, True)
df.index = data.keys()
>>> print(df)
Building Size: Price: ... Cap Rate: Lot Size:
1 9,161 SF $3.17 SF/Mo ... NaN NaN
2 11,332 SF $1.25 SF/Mo ... NaN NaN
3 2,410 SF 2521740 ... 0.0575 76,666 SF
4 59,095 SF $0.63 SF/Mo ... NaN NaN
[4 rows x 9 columns]