【问题标题】:Select a subset of a dataframe based on conditions : category and note根据条件选择数据框的子集:类别和注释
【发布时间】:2022-10-14 16:43:06
【问题描述】:

我正在尝试选择满足以下条件的数据框的子集:

  • 对于同一类别,只保留最高音符的行,
  • 如果 category=na 保留该行

这是我的数据框示例:

预期结果:

什么是有效的方法?谢谢

【问题讨论】:

    标签: python pandas dataframe filtering subset


    【解决方案1】:

    利用:

    df1 = df.sort_values(['category_id','note'])
    
    df1 = df1[~df.duplicated(['category_id']) | df1['category_id'].isna()].sort_index()
    print (df1)
       book_id category_id  note
    0      id1          c1     2
    3      id4          c2     4
    4      id5         NaN     1
    5      id6         NaN     7
    7      id8          c3     2
    8      id9         NaN     8
    9     id10         NaN     4
    10    id11         NaN     9
    

    【讨论】:

      【解决方案2】:

      尝试:

      res = df.sort_values('note', ascending=False)
      res = res[(~res.duplicated('category_id')) | (res['category_id'].isna())]
          .sort_index()
      
      print(res)
      
         book_id category_id  note
      1      id2          c1     5
      4      id5         NaN     1
      5      id6         NaN     7
      6      id7          c2     6
      7      id8          c3     2
      8      id9         NaN     8
      9     id10         NaN     4
      10    id11         NaN     9
      

      【讨论】:

        【解决方案3】:

        排序具有 O(n*logn) 复杂度,因此最好尽可能使用线性时间方法。

        您可以将boolean indexing 与两个掩码一起使用:

        # is the row a NA?
        m1 = df['category_id'].isna()
        # is the row the max value for a non NA?
        m2 = df.index.isin(df.groupby('category_id')['note'].idxmax())
        
        # keep if any condition is met
        out = df.loc[m1|m2]
        

        输出:

           book_id category_id  note
        1      id2          c1     5
        4      id5         NaN     1
        5      id6         NaN     7
        6      id7          c2     6
        7      id8          c3     2
        8      id9         NaN     8
        9     id10         NaN     4
        10    id11         NaN     9
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-06-08
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-03-02
          • 2020-07-05
          • 1970-01-01
          • 2021-01-25
          相关资源
          最近更新 更多