簡體   English   中英

Pandas 級別名稱的多索引切片

[英]Pandas multi-index slices for level names

最新版本Pandas支持多索引切片器。 但是,需要知道不同級別的 integer 位置才能正確使用它們。

例如以下內容:

idx = pd.IndexSlice
dfmi.loc[idx[:,:,['C1','C3']],idx[:,'foo']]

假設我們知道第三行級別是我們要使用C1C3索引的行,第二列級別是我們要使用foo索引的行。

有時我知道級別的名稱,但不知道它們在多索引中的位置。 在這種情況下有沒有辦法使用多索引切片?

例如,假設我知道我想在每個級別名稱上應用哪些切片,例如作為字典:

'level_name_1' -> ':' 
'level_name_2' -> ':'
'level_name_3' -> ['C1', 'C3']

但我不知道多索引中這些級別的 position(深度)。 Pandas 是否為此內置了索引機制?

如果我知道關卡名稱但不知道它們的 position,我還能以某種方式使用pd.IndexSlice對象嗎?

PD:我知道我可以使用reset_index()然后只使用平面列,但我想避免重置索引(即使是暫時的)。 我也可以使用query ,但query要求索引名稱與 Python 標識符兼容(例如沒有空格等)。


我所看到的最接近的是:

df.xs('C1', level='foo')

其中foo是級別的名稱, C1是感興趣的值。

我知道xs支持多個鍵,例如:

df.xs(('one', 'bar'), level=('second', 'first'), axis=1)

但它支持切片或范圍(就像pd.IndexSlice一樣)。

這仍然是一個未解決的增強問題,請參見此處 它非常直接支持這一點。 請求拉動請求!

您可以輕松地執行此操作:

In [11]: midx = pd.MultiIndex.from_product([list(range(3)),['a','b','c'],pd.date_range('20130101',periods=3)],names=['numbers','letters','dates'])

In [12]: midx.names.index('letters')
Out[12]: 1

In [13]: midx.names.index('dates')
Out[13]: 2

這是一個完整的例子

In [18]: df = DataFrame(np.random.randn(len(midx),1),index=midx)

In [19]: df
Out[19]: 
                                   0
numbers letters dates               
0       a       2013-01-01  0.261092
                2013-01-02 -1.267770
                2013-01-03  0.008230
        b       2013-01-01 -1.515866
                2013-01-02  0.351942
                2013-01-03 -0.245463
        c       2013-01-01 -0.253103
                2013-01-02 -0.385411
                2013-01-03 -1.740821
1       a       2013-01-01 -0.108325
                2013-01-02 -0.212350
                2013-01-03  0.021097
        b       2013-01-01 -1.922214
                2013-01-02 -1.769003
                2013-01-03 -0.594216
        c       2013-01-01 -0.419775
                2013-01-02  1.511700
                2013-01-03  0.994332
2       a       2013-01-01 -0.020299
                2013-01-02 -0.749474
                2013-01-03 -1.478558
        b       2013-01-01 -1.357671
                2013-01-02  0.161185
                2013-01-03 -0.658246
        c       2013-01-01 -0.564796
                2013-01-02 -0.333106
                2013-01-03 -2.814611

這是您的關卡名稱 - >切片

In [20]: slicers = { 'numbers' : slice(0,1), 'dates' : slice('20130102','20130103') }

這會創建一個空的索引器(選擇所有內容)

In [21]: indexer = [ slice(None) ] * len(df.index.levels)

添加切片器

In [22]: for n, idx in slicers.items():
              indexer[df.index.names.index(n)] = idx

並選擇(這必須是一個元組,但是我們必須修改它是一個開始的列表)

In [23]: df.loc[tuple(indexer),:]
Out[23]: 
                                   0
numbers letters dates               
0       a       2013-01-02 -1.267770
                2013-01-03  0.008230
        b       2013-01-02  0.351942
                2013-01-03 -0.245463
        c       2013-01-02 -0.385411
                2013-01-03 -1.740821
1       a       2013-01-02 -0.212350
                2013-01-03  0.021097
        b       2013-01-02 -1.769003
                2013-01-03 -0.594216
        c       2013-01-02  1.511700
                2013-01-03  0.994332

我為此使用自定義 function。 名稱為sel ,靈感來自同名的 xarray 方法。

def sel(df, /, **kwargs):
    """
    Select into a DataFrame by MultiIndex name and value

    This function is similar in functionality to pandas .xs() and even more similar (in interface) to xarray's .sel().

    Example:

    >>> index = pd.MultiIndex.from_product([['TX', 'FL', 'CA'],
    ...                                     ['North', 'South']],
    ...                                    names=['State', 'Direction'])
    >>> df = pd.DataFrame(index=index,
    ...                   data=np.random.randint(0, 10, (6,4)),
    ...                   columns=list('abcd'))
    >>> sel(df, State='TX')
                        a  b  c  d
       State Direction
       TX    North      5  5  9  5
             South      0  6  8  2
    >>> sel(df, State=['TX', 'FL'], Direction='South')
                        a  b  c  d
       State Direction
       TX    South      0  6  8  2
       FL    South      6  7  5  2

    indexing syntax is index_name=indexer where the indexer can be:

    - single index value
    - slice by using the slice() function
    - a list of index values
    - other indexing modes supported by indivdual axes in .loc[]

    Unnamed index levels can be selected using names _0, _1 etc where the number is the index level.

    raises KeyError if an invalid index level name is used.
    """
    # argument checking
    available_names = [name or f'_{i}' for i, name in enumerate(df.index.names)]
    extra_args = set(kwargs.keys()) - set(available_names)
    if extra_args:
        raise KeyError(f"Invalid keyword arguments, no index(es) {extra_args} in dataframe. Available indexes: {available_names}.")
    # compute indexers per index level
    index_sel = tuple(kwargs.get(name or f'_{i}', slice(None)) for i, name in enumerate(df.index.names))
    if not index_sel:
        index_sel = slice(None)
    # Fixup for single level indexes
    if len(df.index.names) == 1 and index_sel:
        index_sel = index_sel[0]
    return df.loc[index_sel, :]

不幸的是, .query()方法不以相同的方式支持常規切片,但它確實支持按名稱和間隔選擇索引級別。 因此,它有資格作為您問題的另一個答案。

Query 支持使用反引號引用索引名稱,如下所示。

# Get an example dataset from seaborn
import pandas as pd
import seaborn as sns
df = sns.load_dataset("penguins")
df = df.rename_axis("numerical index / ħ")  # strange name to show escaping.
df = df.set_index(['species', 'island'], append=True)


# Working examples
# less than
df.query("`numerical index / ħ` < 100")

# range
slc = range(9, 90)
df.query("`numerical index / ħ` in @slc")

# Subsets
islands = ['Dream', 'Biscoe']
df.query("island in @islands and species == 'Adelie'")

企鵝示例表

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM