【问题标题】:Remove duplicates indices in multiindex regardless of order无论顺序如何,都删除多索引中的重复索引
【发布时间】:2018-01-04 21:04:18
【问题描述】:

使用多索引的简单pd.Series

#create the multiindex and data
mult = pd.MultiIndex.from_product([[1,2,3],[1,2,3]],names=['factor1','factor2'])
data = np.arange(1,4)*np.arange(1,4)[:,np.newaxis]

#create the series
ser = (pd.Series(data.ravel(),
                index=mult,
                name='product')
       .sort_values(ascending=False))

print(ser)
factor1  factor2
3        3          9
         2          6
2        3          6
         2          4
3        1          3
1        3          3
2        1          2
1        2          2
         1          1
Name: product, dtype: int64

如何删除重复的索引,不管顺序,以便最终系列是

factor1  factor2
3        3          9
         2          6
2        2          4
3        1          3
2        1          2
1        1          1
Name: product, dtype: int64

这个想法是2*33*2 是相同的因素,所以我们想去掉一个。我试过drop_duplicates,但这消除了任何重复的产品,无论它们的索引如何(所以1*02*0 将被视为重复)。

【问题讨论】:

    标签: pandas indexing duplicates series multi-index


    【解决方案1】:

    哈克

    ser[~pd.DataFrame(np.sort(np.array(ser.index.tolist()), 1)).duplicated().values]
    
    factor1  factor2
    3        3          9
             2          6
    2        2          4
    3        1          3
    2        1          2
    1        1          1
    Name: product, dtype: int64
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-25
      • 1970-01-01
      • 2021-03-22
      • 1970-01-01
      • 2018-10-17
      • 2013-09-08
      • 2019-02-22
      相关资源
      最近更新 更多