【问题标题】:Python multiindex slicing with repetitive values具有重复值的 Python 多索引切片
【发布时间】:2021-02-11 02:27:54
【问题描述】:

我在使用带有重复多索引的 pandas 切片数据时遇到问题。

假设我有一张桌子(A 和 B 是索引)

A B C
1 1 11
1 2 12
1 3 13
2 1 21
2 2 22
2 3 23

and so on

And to vectors
a = [1, 2, 3, 1, 2, 1, 2 ]
b = [3, 2, 1, 3, 2, 1, 3 ]

我想以某种方式对表格进行切片,以返回向量 c,其值与向量 a 和 b 的索引一致。

c = [13, 22, 31, 13, 22, 11, 23] 

我唯一想到的就是旋转这张表并得到:

A B1 B2 B3
1 11 12 13
2 21 22 23
3 31 32 33

通过 loc 将一个索引应用于 A 列以获得正确的行,与指示矩阵相乘以为每一行选择正确的列,并与 cumsum 获得一个向量(使用另一个切片)。 我确信必须有更简单的方法来做到这一点,但我找不到正确的方法来做到这一点

【问题讨论】:

    标签: python pandas numpy multi-index


    【解决方案1】:

    您可以使用 ab 数组创建一个新的 MultiIndex 然后 reindex 您的数据框:

    样本数据

    import pandas as pd
    
    index = pd.MultiIndex.from_product([[1,2,3], [1,2,3]])
    df = pd.DataFrame({"C": [11, 12, 13, 21, 22, 23, 31, 32, 33]}, index=index)
    
    print(df) # dataframe with 2-level index and 1 column "C"
          C
    1 1  11
      2  12
      3  13
    2 1  21
      2  22
      3  23
    3 1  31
      2  32
      3  33
    

    方法

    • 从您的 ab 数组创建新的 MultiIndex
    • 将数据框(或仅感兴趣的列)与此新索引对齐
    a = [1, 2, 3, 1, 2, 1, 2 ]
    b = [3, 2, 1, 3, 2, 1, 3 ]
    
    new_index = pd.MultiIndex.from_arrays([a, b])
    new_c = df["C"].reindex(new_index)
    
    print(new_c.to_numpy())
    [13 22 31 13 22 11 23]
    

    方法二

    您还可以将 ab 数组压缩在一起,然后简单地使用 .loc 对数据框进行切片:

    # Select the rows specified by combinations of a, b; in column "C"
    new_c = df.loc[zip(a, b), "C"]
    
    print(new_c.to_numpy())
    [13 22 31 13 22 11 23]
    

    【讨论】:

      【解决方案2】:

      一个选项是merge:

       pd.DataFrame({'A':a,'B':b}).merge(df, on=['A','B'], how='left')['C']
      

      输出(注意NaN的值对应于df中没有数据的地方):

      0    13.0
      1    22.0
      2     NaN
      3    13.0
      4    22.0
      5    11.0
      6    23.0
      Name: C, dtype: float64
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-03-16
        • 2012-02-24
        • 1970-01-01
        • 2019-03-29
        • 2014-02-24
        • 2021-07-05
        相关资源
        最近更新 更多