2014-09-11 108 views
1

我很努力重新索引多索引。下面的示例代碼:重新索引多索引問題

rng = pd.date_range('01/01/2000 00:00', '31/12/2004 23:00', freq='H') 
ts = pd.Series([h.dayofyear for h in rng], index=rng) 
daygrouped = ts.groupby(lambda x: x.dayofyear) 
daymean = daygrouped.mean() 
myindex = np.arange(1,367) 
myindex = np.concatenate((myindex[183:],myindex[:183])) 
daymean.reindex(myindex) 

給出(預期):

184 184 
185 185 
186 186 
187 187 
... 
180 180 
181 181 
182 182 
183 183 
Length: 366, dtype: int64 

,但如果我創建了一個multindex:

hourgrouped = ts.groupby([lambda x: x.dayofyear, lambda x: x.hour]) 
hourmean = hourgrouped.mean() 
myindex = np.arange(1,367) 
myindex = np.concatenate((myindex[183:],myindex[:183])) 
hourmean.reindex(myindex, level=1) 

我得到:

1 1  1 
    2  1 
    3  1 
    4  1 
... 
366 20 366 
    21 366 
    22 366 
    23 366 
Length: 8418, dtype: int64 

任何想法在我的錯誤? - 謝謝。

貝文

回答

1

首先,你必須指定level=0而不是1(因爲它是第一級 - >從零開始的索引 - > 0)。
但是,還有一個問題:重建索引的作品,但似乎並沒有保持在一個多指標的情況下提供索引的順序:

In [54]: hourmean.reindex([5,4], level=0) 
Out[54]: 
4 0  4 
    1  4 
    2  4 
    3  4 
    4  4 
    ... 
    20 4 
    21 4 
    22 4 
    23 4 
5 0  5 
    1  5 
    2  5 
    3  5 
    4  5 
    ... 
    20 5 
    21 5 
    22 5 
    23 5 
dtype: int64 

因此獲得指數著作的一個新的子集,但它與原來的順序相同,而不是新提供的索引。
這可能是在一定的水平reindex的錯誤(我開了一個問題來討論這樣的:https://github.com/pydata/pandas/issues/8241


一個解決方案現在重新索引你的系列,是創建一個多指標,並與重新索引(所以不在指定的級別上,但是具有完整的索引,這確實保持了訂單)。這樣做是很容易與MultiIndex.from_product因爲你已經有myindex

In [79]: myindex2 = pd.MultiIndex.from_product([myindex, range(24)]) 

In [82]: hourmean.reindex(myindex2) 
Out[82]: 
184 0  184 
    1  184 
    2  184 
    3  184 
    4  184 
    5  184 
    6  184 
    7  184 
    8  184 
    9  184 
    10 184 
    11 184 
    12 184 
    13 184 
    14 184 
... 
183 9  183 
    10 183 
    11 183 
    12 183 
    13 183 
    14 183 
    15 183 
    16 183 
    17 183 
    18 183 
    19 183 
    20 183 
    21 183 
    22 183 
    23 183 
Length: 8784, dtype: int64 
+0

重指數級我也有它0(它改爲1,看看我是否能得到任何工作......)。謝謝你非常好地回答我的問題,併爲我提供了更多的理解。 – bevanj 2014-09-12 01:22:59