如何将组合低频类别/值的 python 代码转换为可应用于任何 pandas 数据帧列的函数?



>对于此解决方案 有没有一种简单的方法可以在函数中定义此代码,以便我可以将其应用于任何数据帧列。

解决方案应该在Series.value_counts中用normalize=True来简化:

def replace_thresh(df, col, thresh, new_val):
s = df[col].value_counts(normalize=True).mul(100)
df[col] = np.where(df[col].isin(s.index[s < thresh]), new_val, df[col])
return df
df = replace_thresh(df, 'col', 1, 'Other')

相关内容

最新更新