gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 06:27:55 25 4
gpt4 key购买 nike

为此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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com