MultiIndex和DateTime

时间:2013-08-01 06:36:07

标签: python pandas

我有一个已排序的CSV数据集,其中有四列我想用作MultiIndex,包括两个DateTime列:

Alex,Beta,2011-03-01 00:00:00,2011-03-03 00:00:00,A,8,11.4
Alex,Beta,2011-03-03 00:00:00,2011-03-05 00:00:00,B,10,17.2
Alex,Beta,2011-03-05 00:00:00,2011-03-07 00:00:00,A,3,11.4
Alex,Beta,2011-03-07 00:00:00,2011-03-09 00:00:00,B,7,17.2
Alex,Orion,2011-03-02 00:00:00,2011-03-04 00:00:00,A,4,11.4
Alex,Orion,2011-03-03 00:00:00,2011-03-05 00:00:00,B,6,17.2
Alex,Orion,2011-03-04 00:00:00,2011-03-06 00:00:00,A,3,11.4
Alex,Orion,2011-03-05 00:00:00,2011-03-07 00:00:00,B,11,17.2
Alex,ZZYZX,2011-03-02 00:00:00,2011-03-05 00:00:00,A,10,11.4
Alex,ZZYZX,2011-03-04 00:00:00,2011-03-07 00:00:00,A,15,11.4
Alex,ZZYZX,2011-03-06 00:00:00,2011-03-09 00:00:00,B,20,17.2
Alex,ZZYZX,2011-03-08 00:00:00,2011-03-11 00:00:00,B,5,17.2

我可以使用read_csv加载它并分层显示DataFrame。但索引它是另一回事。我最接近的是,pandas不喜欢在这里使用DateTime索引。如果我注释掉index_col中的DateTime标签以及索引语句(df.loc)中的相应条目,它可以正常工作。

有什么想法吗?

#!/usr/bin/env python

import numpy as np
import pandas as pd

pd.set_option('display.height',            400)
pd.set_option('display.width',             400)
pd.set_option('display.max_rows',         1000)
pd.set_option('display.max_columns',        30)
pd.set_option('display.line_width',        200)

try:
    df = pd.read_csv(
        './sales.csv',
        header =                          None,
        na_values =                   ['NULL'],
        names = [
            'salesperson',
            'customer',
            'invoice_date',
            'ship_date',
            'product',
            'quantity',
            'price',
        ],
        index_col = [
            'salesperson',
            'customer',
            'invoice_date',
            'ship_date',
        ],
        parse_dates = [
            'invoice_date',
            'ship_date',
        ],
    )
except Exception as e:
    print(e)

try:
    print(df)
    print(df.loc[(
        'Alex',                    # salesperson
        'ZZYZX',                   # customer
        '2011-03-02 00:00:00',     # invoice_date
        '2011-03-05 00:00:00',     # ship_date
    )])
except Exception as e:
    print(e)

1 个答案:

答案 0 :(得分:1)

似乎工作正常,我得到一个合适的df。虽然我会尝试避免每个列表中的空条目。

如果您使用parse_dates,则还应使用正确的datetime对象访问这些列:

df.loc[('Alex','ZZYZX',pd.datetime(2011,3,2),pd.datetime(2011,3,5))]

product        A
quantity      10
price       11.4
Name: (Alex, ZZYZX, 2011-03-02 00:00:00, 2011-03-05 00:00:00), dtype: object