为此solution 有没有一种简单的方法可以在函数中定义此代码,以便我可以将其应用于任何数据框列。
最佳答案
解决方案应该使用 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')
关于python - 如何将结合低频类别/值的 python 代码转换为可应用于任何 pandas 数据框列的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60034119/