设置pandas中现有数据帧的多索引

时间:2014-06-04 15:22:45

标签: python pandas

我有DataFrame看起来像

  Emp1    Empl2           date       Company
0    0        0     2012-05-01         apple
1    0        1     2012-05-29         apple
2    0        1     2013-05-02         apple
3    0        1     2013-11-22         apple
18   1        0     2011-09-09        google
19   1        0     2012-02-02        google
20   1        0     2012-11-26        google
21   1        0     2013-05-11        google

我想通过公司和日期为MultiIndex设置DataFrame。目前它有一个默认索引。我正在使用df.set_index(['Company', 'date'], inplace=True)

df = pd.DataFrame()
for c in company_list:
        row = pd.DataFrame([dict(company = '%s' %s, date = datetime.date(2012, 05, 01))])
        df = df.append(row, ignore_index = True)
        for e in emp_list:
            dataset  = pd.read_sql("select company, emp_name, date(date), count(*) from company_table where  = '"+s+"' and emp_name = '"+b+"' group by company, date, name LIMIT 5 ", con)
                if len(dataset) == 0:
                row = pd.DataFrame([dict(sitename='%s' %s, name = '%s' %b, date = datetime.date(2012, 05, 01), count = np.nan)])
                dataset = dataset.append(row, ignore_index=True)
            dataset = dataset.rename(columns = {'count': '%s' %b})
            dataset = dataset.groupby(['company', 'date', 'emp_name'], as_index = False).sum()

            dataset = dataset.drop('emp_name', 1)
            df = pd.merge(df, dataset, how = '')
            df = df.sort('date', ascending = True)
            df.fillna(0, inplace = True)

df.set_index(['Company', 'date'], inplace=True)            
print df

但是当我打印此DataFrame时,会打印None。我从stackoverflow中看到了这个解决方案。这不是正确的做法吗?此外,我想改组列公司和日期的位置,以便公司成为第一个索引,日期成为层次结构中的第二个。关于这个的任何想法?

1 个答案:

答案 0 :(得分:53)

当你传入in in in对原始变量进行更改并返回None,并且函数返回修改后的数据帧时,它将返回None。

is_none = df.set_index(['Company', 'date'], inplace=True)
df  # the dataframe you want
is_none # has the value None

所以当你有一个像:

这样的行
df = df.set_index(['Company', 'date'], inplace=True)

首先修改df ...但是它会将df设置为无!

也就是说,您应该使用以下行:

df.set_index(['Company', 'date'], inplace=True)