【问题标题】:pandas category: keep only most common ones and replace rest with NaNpandas 类别:只保留最常见的并用 NaN 替换 rest
【发布时间】:2019-10-22 05:58:30
【问题描述】:

pd.Seriesdtype=category 中,我有 253 个唯一值。其中一些经常发生,而另一些只发生一次或两次。现在我想只保留其中的前 10 名,并将其余的替换为 np.nan

我已经到了top = df['cats'].value_counts().head(10) 来创建我想要保留的类别。但是现在呢?

类似于df['cats'].apply(cat_replace, args=top)

def cat_replace(c, top):
    if c in top:
        return c
    else:
        return np.nan

但是,这对我来说看起来不太“熊猫”,我觉得有更好的方法。有更好的建议吗?

【问题讨论】:

    标签: python pandas categorical-data


    【解决方案1】:
    # Sample data.
    df = pd.DataFrame(
        {'cats': pd.Categorical(
            list('abcdefghij') * 5
            + list('klmnopqrstuvwxyz'))}
    )
    
    top_n = 10
    top_cats = df['cats'].value_counts().head(top_n).index.tolist()
    df.loc[~df['cats'].isin(top_cats), 'cats'] = np.nan
    

    【讨论】:

    • 只是想提供帮助:cats = ['Abyssinian', 'Bobtail', 'Curl', 'Shorthair', 'Wirehair', 'Balinese', 'Bengal', 'Bombay', 'Burmese', 'Rex', 'Burmilla', 'Mau', 'Havana', 'Javanese', 'Korat', 'LaPerm']; np.random.seed([3, 1415]); df = pd.DataFrame({'cats': np.random.choice(cats, 1000)})
    【解决方案2】:

    抄袭

    How can I keep the rows of a pandas data frame that match a particular condition using value_counts() on multiple columns

    你可以考虑做类似的事情

    top = set(df['cats'].value_counts().head(10))
    df['cats'].apply(top.__contains__)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-12-01
      • 1970-01-01
      • 2022-10-31
      • 2021-04-13
      • 2022-10-05
      • 2017-08-01
      • 2023-03-04
      相关资源
      最近更新 更多