10

次の pandas データ フレームがあるとします。

df = pd.DataFrame({'A': ['foo' ] * 3 + ['bar'],
         'B': ['w','x']*2,
         'C': ['y', 'z', 'a','a'],
         'D': rand.randn(4),
          })

print df.to_string()
"""
     A  B  C           D
0  foo  w  y  0.06075020
1  foo  x  z  0.21112476
2  foo  w  a  0.01652757
3  bar  x  a  0.17718772
"""

bar,w の組み合わせがないことに注目してください。次の場合:

pv0 = pandas.pivot_table(df, rows=['A','B'],cols=['C'], aggfunc=numpy.sum)

pv0.ix['bar','x'] #returns result

pv0.ix['bar','w'] #key error though i would like it to return all Nan's

pv0.index #returns 
[(bar, x), (foo, w), (foo, x)]

foo,x の場合のように列 'C' に少なくとも 1 つのエントリがある限り ('C' 列には 'z' の値しかない)、' の他の列値に対して NaN を返します。 C' は foo,x には存在しません (例: 'a','y')

私が望むのは、すべての列値のデータがないものであっても、すべてのマルチインデックスの組み合わせを持つことです。

pv0.index #I would like it to return
[(bar, w), (bar, x), (foo, w), (foo, x)]

.ix コマンドを try/except ブロックでラップできますが、パンダがこれを自動的に埋める方法はありますか?

4

1 に答える 1

7

reindex()メソッドを使用できます。

>>> df1 = pd.pivot_table(df, rows=['A','B'], cols='C', aggfunc=np.sum)
>>> df1
              D                   
C             a        y         z
A   B                             
bar x  0.161702      NaN       NaN
foo w  0.749007  0.85552       NaN
    x       NaN      NaN  0.458701

>>> index = list(iter.product(df['A'].unique(), df['B'].unique()))
>>> df1.reindex(index)
              D                   
C             a        y         z
foo w  0.749007  0.85552       NaN
    x       NaN      NaN  0.458701
bar w       NaN      NaN       NaN
    x  0.161702      NaN       NaN
于 2013-11-13T15:49:03.413 に答える