折叠许多类别的变量
Collapsing many categories of variable
我有一个 df
,其中包含两个具有许多 (>2000) 个类别的分类变量。其中一类变量'installer',占了数据的很大一部分:
DWE 35.397980
Government 3.073401
RWE 2.017508
Commu 1.814141
DANIDA 1.757576
...
我怎样才能保留前三个类别并将其余类别折叠到名为 'other' 的类别中,而不必全部列出?
注意:我之前对基数较低的变量使用过替换,但必须列出我要替换的所有值。
我试过:
unique_values= df['installer'].unique()
for unique in unique_values:
if unique != 'DWE' or unique != 'Government' or unique != 'RWE':
df['installer'] = df['installer'].replace(unique, 'other')
先使用value_counts
抓取重复次数最多的三个,然后过滤并评估'Other'
怎么样?
categories_to_keep = df['installer'].value_counts().index[:3]
df.loc[
(~df.installer.isin(categories_to_keep)), 'installer'
] = 'Other'
我有一个 df
,其中包含两个具有许多 (>2000) 个类别的分类变量。其中一类变量'installer',占了数据的很大一部分:
DWE 35.397980
Government 3.073401
RWE 2.017508
Commu 1.814141
DANIDA 1.757576
...
我怎样才能保留前三个类别并将其余类别折叠到名为 'other' 的类别中,而不必全部列出?
注意:我之前对基数较低的变量使用过替换,但必须列出我要替换的所有值。
我试过:
unique_values= df['installer'].unique()
for unique in unique_values:
if unique != 'DWE' or unique != 'Government' or unique != 'RWE':
df['installer'] = df['installer'].replace(unique, 'other')
先使用value_counts
抓取重复次数最多的三个,然后过滤并评估'Other'
categories_to_keep = df['installer'].value_counts().index[:3]
df.loc[
(~df.installer.isin(categories_to_keep)), 'installer'
] = 'Other'