如何在pandas数据透视表中重复索引,使得nan填充无记录行?

时间:2016-03-01 03:03:25

标签: python pandas pivot-table

原谅我的措词不好 - 我不确定如何说出来。

鉴于此pandas数据透视表,

df = pd.DataFrame({'col1': list('AABB'),
                   'col2': list('acab'),
                   'values': [1,3,4,5]})
pt = pd.pivot_table(df,
                    index=['col1', 'col2'],
                    values='values',
                    aggfunc=sum)

输出:

col1  col2
A     a       1
      c       3
B     a       4
      b       5

如何使数据透视表输出:

col1  col2
A     a        1
      b      NaN
      c        3
B     a        4
      b        5
      c      NaN

1 个答案:

答案 0 :(得分:2)

如果您将列转换为category数据类型(pandas 0.15中的新数据!),您将获得您所追求的聚合:

df.col2 = df.col2.astype('category')
In [378]: df.groupby(['col1','col2']).sum()
Out[378]:
           values
col1 col2
A    a          1
     b        NaN
     c          3
B    a          4
     b          5
     c        NaN