【问题标题】:Drop duplicates of permuted multi-index删除置换多索引的重复项
【发布时间】:2018-10-17 19:53:58
【问题描述】:

我有一个如下的数据框:

           Correlations       adf
FITB RF        0.984395 -5.484766
WAT  SWK       0.981778 -5.465284
SWK  WAT       0.981778 -5.420976
RF   FITB      0.984395 -5.175268
MCO  BK        0.973801 -4.919812

并且我想过滤索引,以便数据框删除任何重复的值,即使它们被置换。因此,上述数据框将变为

           Correlations       adf
FITB RF        0.984395 -5.484766
WAT  SWK       0.981778 -5.465284
MCO  BK        0.973801 -4.919812

我找不到对大型数据框执行此操作的有效方法。非常感谢任何帮助!

【问题讨论】:

    标签: python pandas dataframe filtering multi-index


    【解决方案1】:

    可以使用以下函数对索引进行归一化:

    def normalizeIndex(x):
        splittedString = list(filter(None, x.split(" ")))#split the input string into token with blank space separator and remove empty results
        splittedString.sort()#sort the token list
        return " ".join(splittedString) #return normalized string concatenating ordered token list
    

    在将 df 分组到索引上并选择第一次出现之前,可以将函数应用于索引(无论如何可以应用进一步的分组选项):

        df = pd.DataFrame({'Correlations': [0.984395, 0.981778,0.981778,0.984395,0.973801,],
                       'adf':[-5.484766,-5.465284,-5.420976,-5.175268,-4.919812]},
    
                      index=['FITB RF','WAT  SWK','SWK  WAT','RF   FITB','MCO  BK',])
    
        df.index = df.index.map(lambda x: normalizeIndex(x)) #Apply reordering function to df index
        df = df.groupby(df.index).first() #Group the resulting dataframe, by index and, take the first occurence
        print(df)
    

    出来:

             Correlations       adf
    BK MCO       0.973801 -4.919812
    FITB RF      0.984395 -5.484766
    SWK WAT      0.981778 -5.465284
    

    【讨论】:

      【解决方案2】:

      您可以使用sorted + duplicated

      df[~pd.DataFrame(list(map(sorted,df.index.values))).duplicated().values]
                Correlations       adf
      FITB RF       0.984395 -5.484766
      WAT  SWK      0.981778 -5.465284
      MCO  BK       0.973801 -4.919812
      

      【讨论】:

        【解决方案3】:

        您可以利用np.sort + pd.DataFrame.duplicated

        m = pd.DataFrame(np.sort(df.index.tolist(), axis=1)).duplicated()
        df[~(m.values)]
        
                  Correlations       adf
        FITB RF       0.984395 -5.484766
        WAT  SWK      0.981778 -5.465284
        MCO  BK       0.973801 -4.919812
        

        或者,以类似的方式,使用pd.MultiIndex.duplicated

        m = pd.MultiIndex.from_tuples(
            [tuple(x) for x in np.sort(df.index.tolist(), axis=1)]
        ).duplicated()
        df[~m]
        
        
                  Correlations       adf
        FITB RF       0.984395 -5.484766
        WAT  SWK      0.981778 -5.465284
        MCO  BK       0.973801 -4.919812
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2013-09-08
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-11-21
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多