【问题标题】:How can I organize my data [closed]如何组织我的数据[关闭]
【发布时间】:2015-12-21 17:04:53
【问题描述】:

假设我有一个由客户编号、商店编号、名字、姓氏和地址组成的列表,格式如下:

11, 2, Lisa, Anderson, NewYork

13, 4, John, Smith, Alabama

54, 2, Lucy, Nicholsson, NewYork

etc.

对我来说,在 python 中组织这些数据的最佳方式是什么,以便我可以轻松访问它,这样我就可以执行诸如输入客户编号和输出位置等操作,以及其他类似操作的衍生物。

【问题讨论】:

  • 用这些属性定义一个class,然后创建方法来处理和返回你想要的信息。
  • 我很确定Python tutorial 会为您提供所有选项。你有具体的问题理解/应用吗?

标签: python data-management


【解决方案1】:

您可以使用pandas。它提供了类似数据库(或类似电子表格)的表格,可用于存储和查询数据。像这样:

import pandas as pd
df = pd.DataFrame([
        [11, 2, 'Lisa', 'Anderson', 'NewYork'],
        [13, 4, 'John', 'Smith', 'Alabama'],
        [54, 2, 'Lucy', 'Nicholsson', 'NewYork']
         ], columns = ['cl_number', 'store', 'first_name', 'last_name','address'])

df.index=df["cl_number"]
# rows will be indexed with cl_number

df.loc[11]
# returns a record of client with number 11

df.loc[11, 'address']
# returns address of a client with number 11

df[df['address'] == 'NewYork']
# returns a list of all clients with address 'NewYork'

但是,您可能还需要功能齐全的数据库(例如,请参阅SQLite)。

【讨论】:

    【解决方案2】:

    如果您的数据相当一致,并且没有那么多您想要一个成熟的数据库,那么您可以通过namedtuple 取得相当大的进展:

    from collections import namedtuple
    
    Client = namedtuple('Client', ('id', 'storeno', 'first_name', 'last_name',
                                   'location'))
    
    # Read the data
    with open('db.csv') as fi:
        rows = fi.readlines()
    db = {}
    for row in rows:
        f= row.split(',')
        db[int(f[0])] = Client(int(f[0]), int(f[1]), f[2].strip(),
                               f[3].strip(), f[4].strip())
    
    def find(**kwargs):
        """Return a list of all Clients matching a given set of criteria."""
        matches = []
        for client in db.values():
            for k,v in kwargs.items():
                if getattr(client, k) != v:
                    break
            else:
                matches.append(client)
        return matches
    
    # Client with ID 11
    print db[11]
    
    # All clients in New York
    print find(location='NewYork')
    # All clients called Lisa in New York
    print find(location='NewYork', first_name='Lisa')
    

    【讨论】:

      猜你喜欢
      • 2010-10-27
      • 2016-05-25
      • 1970-01-01
      • 2010-10-09
      • 1970-01-01
      • 2015-06-17
      • 1970-01-01
      • 2020-04-28
      • 1970-01-01
      相关资源
      最近更新 更多