分组级别 - python pandas中的multiindex

时间:2016-04-01 20:28:01

标签: python pandas pivot-table multi-index

multiindex中的dataframe pandas看起来是这样的(使用pivot_table创建的):

enter image description here

我需要帮助才能在显示日期日期的日期级别上方(或以下)添加级别,如下所示:

enter image description here

我知道我可以得到这样的日期:

lt.DATE.dt.strftime('%a')
#lt is a dataframe and DATE is a column it.

这是代码重新定义类似的pivot_table:

import pandas as pd
import numpy as np

dlist = pd.date_range('2015-01-01',periods=5)
df = pd.DataFrame(dlist, columns=['DATE'])
df['EC'] = range(7033,7033+len(df))
df['HS'] = np.random.randint(0,9,5)
df['AH'] = np.random.randint(0,9,5)
pv = pd.pivot_table(df, columns=[df.DATE, 'EC'], values=['HS','AH'])
pv = pv.unstack(level=1).unstack(level=0)

1 个答案:

答案 0 :(得分:0)

我得到了解决方案!在这里:

import pandas as pd
import numpy as np

dlist = pd.date_range('2015-01-01',periods=5)
df = pd.DataFrame(dlist, columns=['DATE'])
df['EC'] = range(7033,7033+len(df))
df['HS'] = np.random.randint(0,9,5)
df['AH'] = np.random.randint(0,9,5)
df['DAY'] = df.DATE.dt.strftime('%a')
pv = pd.pivot_table(df, columns=[df.DATE.dt.date, df.DAY, 'EC'], values=['HS','AH'])
pv = pv.unstack(level=[1,2]).unstack(level=0)
pv.to_excel('solution.xlsx')

它产生如下输出:

enter image description here

注意函数unstack并设置一次需要取消堆叠的级别列表。