Python 数据格式中的列表、字典、类与数据帧



我有一个由字符串组成的Python列表,其中包含属性地址和每个属性的多个属性。

'Date of Sale', 'January 1, 2017', 'Phone Number', '111-344-2343', 'Color', 'Brown', 'Garage Size', '2', 'Date Listed', 'September 23, 2016', 'Loan From', 'Example Mortgage Services', 'Street Address', '751 Example Drive', 'City', 'Chicago', 'Number of Windows', 'Attorney', 'Shaping LLP', 'Township', 'Dundee', 'Zip Code', '99999', 'List Price', '$83,301.87', 'Bid Amount', '$110,199.00', 'Miscellaneous', 'Long Driveway', 'Date of Sale', ...

这是一个"条目"。该列表以相同的模式继续贯穿其余属性(每个属性都以"销售日期"开头),但如果字段留空,则会完全跳过它们。例如,如果未出价,则"出价金额"后面直接跟着"杂项",而不是金额。

目标是能够轻松解析信息。例如,我想列出所有我没有出价的房产。

主要问题是使用什么数据格式(class、列表、字典或数据帧):

class Property(object):
def __init__(self,dateOfSale,phoneNumber...):
self.dateOfSale = 'dateOfSale'
self.phoneNumber = 'phoneNumber'
...

但我不确定我将如何利用它来获取有关多个属性的信息。

将有关每个属性的所有信息合并到一个list项中。不过,我不确定您将如何查看此信息。

使用地址键的dictionary,以及值的所有其他信息,尽管这似乎也不容易迭代。

利用熊猫dataframe.我将不得不做更多的研究,但似乎"电子表格"数据在这种格式下效果很好。

您当前的数据结构非常笨拙,因此我建议您首先将其分解并为每个条目制作字典。您可以稍后将字典列表处理为另一个更复杂的数据结构(如DataFrame),但首先进行低级处理要容易得多。

以下是将单个长字符串列表转换为字典列表的方法:

raw_data = ['Date of Sale', 'January 1, 2017',
'Phone Number', '111-344-2343',
'Color', 'Brown',
'Garage Size', '2',
'Date Listed', 'September 23, 2016',
'Loan From', 'Example Mortgage Services',
'Street Address', '751 Example Drive',
'City', 'Chicago',
'Number of Windows', '16', # the value was missing for this key, so I made up one
'Attorney', 'Shaping LLP',
'Township', 'Dundee',
'Zip Code', '99999',
'List Price', '$83,301.87',
'Bid Amount', '$110,199.00',
'Miscellaneous', 'Long Driveway',
'Date of Sale', ...] # this is data for two entries (the second is abbreviated)
list_of_dicts = []
for key, value in zip(*[iter(raw_data)]*2): # iterate on pairs of items from the raw list
if key == "Date of Sale":
current_dict = {}  # create a new dict each time we come across a Date of Sale key
list_of_dicts.append(current_dict)
current_dict[key] = value

我对 Pandas 一点经验都没有,但我怀疑你可以很容易地从字典列表中制作数据帧(也许只是通过将列表作为参数传递给DataFrame构造函数,我不确定)。您可能需要传递额外的参数来描述您希望数据包含的所有列,尤其是在并非所有条目都具有所有列的值的情况下。

除非你真的需要做数据分析(KISS原则),否则我不会使用Pandas DataFrame。我可能会使用命名元组列表而不是字典列表,因为它在语法上更干净,例如:

import csv
from collections import namedtuple
Property = namedtuple('Property', 'date_of_sale phone_number ...')
properties = []
with open('propertydata.csv', newline='') as csvfile:
for record in csv.reader(csvfile):
properties.append(Property(*record))

然后,您可以循环访问属性并执行所需的任何操作:

no_bid_properties = [p for p in properties where not p.bid_amount]

最新更新