所以我试图获取占总计数 50% 或更多的非序数分类列的最高值,因此所有其他出现的情况都被替换为“其他”。
values_df = df['column'].value_counts(normalize = True)
total = 0
for i, row in enumerate(values_df.values):
row = round(row,2)
if total <= 0.5:
total+=row
else:
df['column'][i] = 'others'
但是当我 print(df['column'].value_counts()) 时,我没有看到下面的值被更改为其他值。
IIUC,您可以使用
cumsum
计算累计总数,然后进行布尔索引(将 Series 转换为对象后):
values_df = (df['column']
.value_counts(normalize = True)
.round(2)
)
m = values_df.cumsum().gt(0.5)
values_df = values_df.astype(object)
values_df[m] = 'others'