列表与字典对比与Python数据格式的数据框架

时间:2017-06-20 19:03:24

标签: list python-3.x class dictionary dataframe

我有一个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'
        ...

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

OR

将有关每个属性的所有信息合并到一个list项中。我不确定你会如何看待这些信息。

OR

使用地址键的dictionary,以及值的所有其他信息,虽然这看起来不容易迭代。

OR

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

2 个答案:

答案 0 :(得分:2)

您数据的当前结构非常笨拙,因此我建议您首先分解并为每个条目创建字典。您可以稍后将字典列表处理为另一个更复杂的数据结构(如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没有任何经验,但我怀疑你可以很容易地从dicts列表中创建一个数据帧(也许只是将列表作为参数传递给DataFrame构造函数,I& #39;我不确定)。您可能需要传递额外的参数来描述您希望数据包含的所有列,特别是如果并非所有条目都包含所有列的值。

答案 1 :(得分:0)

除非您确实需要进行数据分析(KISS原则),否则我不会使用Pandas DataFrame。我可能会使用namedtuple而不是dict的列表,因为它在语法上更清晰,例如:

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]