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

如何将组合低频类别/值的python代码转换为可应用于任何dataframe列的函数?,python,pandas,data-science,Python,Pandas,Data Science,为此 是否有一种简单的方法在函数中定义此代码,以便我可以将其应用于任何数据帧列 解决方案应简化为normalize=Truein: def替换阈值(df、col、阈值、新值): s=df[col]。值_计数(normalize=True)。mul(100) df[col]=np.where(df[col].isin(s.index[s

为此
是否有一种简单的方法在函数中定义此代码,以便我可以将其应用于任何数据帧列

解决方案应简化为
normalize=True
in:

def替换阈值(df、col、阈值、新值):
s=df[col]。值_计数(normalize=True)。mul(100)
df[col]=np.where(df[col].isin(s.index[s
你能添加一些数据样本吗?链接到另一个问题是不够的,你自己的问题应该独立完成。此外,如果您熟悉如何访问pandas中的特定列,那么将现有代码转换为函数应该一点也不困难。为参数指定一个变量名,用所有硬编码值替换参数,就完成了
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')