>对于此解决方案 有没有一种简单的方法可以在函数中定义此代码,以便我可以将其应用于任何数据帧列。
解决方案应该在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')