import pandas as pd
df = pd.DataFrame({'type':['a','a','a','b','b','b','c','d','e'],
'size': ['s','s','s','m','m','s','l','l','xl']})
for col in ['type','size']:
df = pd.concat([df,
pd.get_dummies(df[col].replace(df.loc[~df[col].isin(df[col].value_counts().nlargest(3).index)][col].unique(),
'other'),
prefix=col)],
axis=1)
输出
type size type_a type_b type_c type_other size_l size_m size_other \
0 a s 1 0 0 0 0 0 0
1 a s 1 0 0 0 0 0 0
2 a s 1 0 0 0 0 0 0
3 b m 0 1 0 0 0 1 0
4 b m 0 1 0 0 0 1 0
5 b s 0 1 0 0 0 0 0
6 c l 0 0 1 0 1 0 0
7 d l 0 0 0 1 1 0 0
8 e xl 0 0 0 1 0 0 1
size_s
0 1
1 1
2 1
3 0
4 0
5 1
6 0
7 0
8 0
1条答案
按热度按时间9rbhqvlz1#
你可以找到
nlargest
按列,并在创建假人时用其他值替换不在前3中的值。输出