2013-05-27 48 views
1

似乎還有大量有關Pandas DataFrames索引的其他問題,但是我還沒有找到一種方法來完成我想要的更改類型。如果我有一個看起來很喜歡的DF在Pandas DataFrame中重新定義索引值

   Value 
Index1 Index2 
0  1  1.1 
1  2  1.2 
2  3  2.4 
3  1  1.3 
4  2  2.2 
5  3  3.1 

我不需要所有的index1都是唯一的。我寧願有類似的東西

   Value 
Index1 Index2 
0  1  1.1 
0  2  1.2 
0  3  2.4 
1  1  1.3 
1  2  2.2 
1  3  3.1 

有沒有辦法做到這一點?我認爲最簡單的方法是將索引1值除以3得到的函數,但不知道如何將函數應用於索引。也許雖然熊貓有它自己的方法來重新定義索引值,使得像這樣的分組在你考慮這兩個索引時仍然是獨一無二的。

回答

5
import io 
import pandas as pd 
text = '''\ 
Index1 Index2 Value 
0  1  1.1 
1  2  1.2 
2  3  2.4 
3  1  1.3 
4  2  2.2 
5  3  3.1''' 

df = pd.read_table(io.BytesIO(text), sep='\s+', index_col=[0, 1]) 
df.index = pd.MultiIndex.from_tuples(
    [(item[0] // 3, item[1]) for item in df.index], 
    names=df.index.names)  
print(df) 

產生

   Value 
Index1 Index2  
0  1   1.1 
     2   1.2 
     3   2.4 
1  1   1.3 
     2   2.2 
     3   3.1 
相關問題