从多索引数据框中选择索引和列的子集

2024-04-25 08:23:53 发布

您现在位置:Python中文网/ 问答频道 /正文

什么是沿索引和列分割多索引数据帧的通用方法?你知道吗

文档是密集的、完整的,值得一读(https://pandas.pydata.org/pandas-docs/stable/user_guide/advanced.html),关于堆栈溢出有许多答案,这些答案回答了如何在“行”或“列”上实现它(这个答案非常全面,Select rows in pandas MultiIndex DataFrame)。但是,我想要一个更直截了当的答案,有同时处理两者的例子。你知道吗

创建多索引数据帧

cols_index = pd.MultiIndex.from_product([['a','b','c'],
    ['x','y','z']], names=['first','second'])
rows_index = pd.MultiIndex.from_product([['d','e','f'],
    ['u','v','w']], names=['third','fourth'])
df = pd.DataFrame(np.random.choice(10, (9,9)), index=rows_index, columns=cols_index)
df
Out[161]: 
first         a           b         
second        c     d     c     d   
third         e  f  e  f  e  f  e  f
fourth fifth                        
j      m      9  8  0  1  5  6  3  5
       n      1  2  3  3  5  5  4  2
       o      5  2  4  7  3  1  0  4
k      m      6  6  3  3  4  4  1  7
       n      0  6  0  9  2  3  7  5
       o      7  8  0  9  7  8  3  4
l      m      4  7  4  3  0  5  6  3
       n      0  4  3  9  9  5  8  4
       o      0  1  8  0  8  9  4  7

我想看到一些例子,这些例子将这个问题分解为索引和列中的级别组合。你知道吗


Tags: 数据答案fromdataframepandasindexnamesproduct
1条回答
网友
1楼 · 发布于 2024-04-25 08:23:53

Here is my generic solution...

使用loc和索引切片器对索引和列级别进行切片

idx=pd.IndexSlice公司你知道吗

选择所有内容-注意“:”对应于索引和列中的级别数

你知道吗测向位置[idx[:,:],idx[:,:,:]

Out[251]: 
first         a           b         
second        c     d     c     d   
third         e  f  e  f  e  f  e  f
fourth fifth                        
j      m      2  9  4  5  6  7  7  5
       n      1  4  2  6  8  0  6  3
       o      2  4  0  2  1  9  9  4
k      m      6  5  0  0  9  3  4  0
       n      3  1  6  4  2  3  0  4
       o      0  7  1  6  9  7  5  7
l      m      2  8  0  8  5  1  8  3
       n      7  3  2  6  9  4  1  7
       o      6  4  7  9  1  3  3  3

选择特定的“单元格”

你知道吗测向位置[idx['j','m'],idx['a','c','f']]

Out[252]: 9

从索引中选择一级,从列中选择一级

你知道吗测向位置[idx[:,'m'],idx[:,'c',:]]

Out[253]: 
first         a     b   
second        c     c   
third         e  f  e  f
fourth fifth            
j      m      2  9  6  7
k      m      6  5  9  3
l      m      2  8  5  1

列级别的唯一组合的子集

你知道吗测向位置[:,idx['b','d','f']]

Out[254]: 
fourth  fifth
j       m        5
        n        3
        o        4
k       m        0
        n        4
        o        7
l       m        3
        n        7
        o        3
Name: (b, d, f), dtype: int32

从子集到索引级别的唯一组合

你知道吗测向位置[idx['k','o',:]

Out[255]: 
first  second  third
a      c       e        0
               f        7
       d       e        1
               f        6
b      c       e        9
              f        7
       d       e        5
              f        7
Name: (k, o), dtype: int32

相关问题 更多 >