2014-01-23 26 views
12

當我有兩個或多個迭代器時,我有一個用於創建Pandas MultiIndex的實用函數,並且我希望這些迭代器中的每個唯一配對值都具有一個索引鍵。它看起來像這樣從iterables的產品中製作一個Pandas MultiIndex?

import pandas as pd 
import itertools 

def product_index(values, names=None): 
    """Make a MultiIndex from the combinatorial product of the values.""" 
    iterable = itertools.product(*values) 
    idx = pd.MultiIndex.from_tuples(list(iterable), names=names) 
    return idx 

,並且可以使用,如:

a = range(3) 
b = list("ab") 
product_index([a, b]) 

要創建

MultiIndex(levels=[[0, 1, 2], [u'a', u'b']], 
      labels=[[0, 0, 1, 1, 2, 2], [0, 1, 0, 1, 0, 1]]) 

這工作完全正常,但它似乎是一個常見的用例,我很驚訝,我必須自己實施。所以,我的問題是,我在Pandas圖書館本身有什麼遺漏/誤解提供了這種功能?

修改即可添加:此功能爲爲MultiIndex.from_product爲0.13.1版本。

+0

AFAICT,你寫道,*應*在大熊貓 –

回答

11

這是一個非常類似的結構(但使用cartesian_product這對於較大的陣列是快於itertools.product

In [2]: from pandas.tools.util import cartesian_product 

In [3]: MultiIndex.from_arrays(cartesian_product([range(3),list('ab')])) 
Out[3]: 
MultiIndex(levels=[[0, 1, 2], [u'a', u'b']], 
      labels=[[0, 0, 1, 1, 2, 2], [0, 1, 0, 1, 0, 1]]) 

可以被添加作爲一個便於學習方法,也許MultiIndex.from_iterables(...)

PLS打開的問題(和PR如果你願意)

僅供參考我很少實際上構建一個多指數「手動」,幾乎總是更容易實際構建一個框架,只是​​。

In [10]: df = DataFrame(dict(A = np.arange(6), 
          B = ['foo'] * 3 + ['bar'] * 3, 
          C = np.ones(6)+np.arange(6)%2) 
         ).set_index(['C','B']).sortlevel() 

In [11]: df 
Out[11]: 
     A 
C B  
1 bar 4 
    foo 0 
    foo 2 
2 bar 3 
    bar 5 
    foo 1 

[6 rows x 1 columns] 
+0

您能不能告訴構建數據幀,然後設置索引的一個小例子便捷功能?換句話說,有沒有比這個問題的答案更好的方法:http://stackoverflow.com/questions/12390336/how-to-fill-the-missing-record-of-pandas-dataframe-in-pythonic- way –

+0

這是一個合理的觀點,我主要在設置一個空數據框時使用它,當我遍歷索引的元素時,這些數據框將被填滿。 – mwaskom

+0

@mwaskom我會說,填充一個空的DataFrame(並遍歷索引)不是慣用的熊貓\ * ...有*可能*是一個更乾淨的方式來做到這一點。 \ * pandastic/pandorable –

相關問題