2013-07-23 55 views

回答

9

一旦我們有一個數據幀

import pandas as pd 
df = pd.read_csv("input.csv", index_col=0) # or from another source 

和一個函數映射每個索引到一個元組(下面,它是用於從這個問題的例子)

def process_index(k): 
    return tuple(k.split("|")) 

我們可以創建一個分層索引通過以下方式:

df.index = pd.MultiIndex.from_tuples([process_index(k) for k,v in df.iterrows()]) 

另一種方法是創建兩列然後將它們設置爲的索引(原始索引將被丟棄):

df['e-mail'] = [x.split("|")[0] for x in df.index] 
df['date'] = [x.split("|")[1] for x in df.index] 
df = df.set_index(['e-mail', 'date']) 

或甚至更短

df['e-mail'], df['date'] = zip(*map(process_index, df.index)) 
df = df.set_index(['e-mail', 'date']) 
+0

這是非常有益的。但是,據我所知,在調用set_index()時,默認值是inplace = False,所以必須使用inplace = True,否則將df指定給自己。 – Moot

+0

@Moot謝謝,更新。無論是錯字還是背單詞(4年前),默認情況下它都是「inplace」。 –

+0

太棒了!但有兩個地方 - 檢查代碼的第一個片段... – Moot

2

我更傾向於將最初讀取此在作爲列(即不是作爲一個指標),那麼你可以使用STR分方法:

csv = '\n'.join(['[email protected]|2013-05-07 05:52:51 +0200, 42'] * 3) 
df = pd.read_csv(StringIO(csv), header=None) 

In [13]: df[0].str.split('|') 
Out[13]: 
0 [[email protected], 2013-05-07 05:52:51 +0200] 
1 [[email protected], 2013-05-07 05:52:51 +0200] 
2 [[email protected], 2013-05-07 05:52:51 +0200] 
Name: 0, dtype: object 

再喂到這一個多指標(也許這是可以做到清潔劑):

m = pd.MultiIndex.from_arrays(zip(*df[0].str.split('|'))) 

刪除第0列和索引設置爲新的多指標:

del df[0] 
df.index = m 

In [17]: df 
Out[17]: 
              1 
[email protected] 2013-05-07 05:52:51 +0200 42 
       2013-05-07 05:52:51 +0200 42 
       2013-05-07 05:52:51 +0200 42 
3

pandas>=0.16.0,我們可以使用.str訪問的指標。這使得以下可能:

df.index = pd.MultiIndex.from_tuples(df.index.str.split('|').tolist()) 

(注:我嘗試了更直觀:pd.MultiIndex.from_arrays(df.index.str.split('|'))但出於某種原因,讓我的錯誤。)