我希望对列进行一次热编码,但仅针对那些非常频繁的编码.所有低于阈值T的都将被放入他们自己的类别中.
我的策略是创建一个"名字" - >"频率"字典.然后将频率转换为字符串.如果字符串不常见,则应使用某些描述性字符串替换它.优选地,我想要具有两个区域/阈值:"less_common"和"rare"或类似的东西.
这是我目前的尝试.我把它分成几行只是为了调试fyi.第3行不起作用.我在Python 3.6中使用conda,
tmp = df["name"].groupby(df["name"])
tmp = tmp.agg(['count'])
tmp['count'] = tmp["count"].apply(lambda x: "Uncommon" if tmp["count"] < 1000.0 else str(x) )
labelDict = tmp.to_dict()
#some code?
df[columnName].replace(labelDict, inplace=True)
pd.get_dummies(df, columns=['name'])
Run Code Online (Sandbox Code Playgroud)
错误:
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
Run Code Online (Sandbox Code Playgroud)
一些示例输入(还有其他列):name = a,a,a,a,b,b,b,c,c,d
这变成了
name | count
a | 4
b | 3
c | 2
d | 1
Let's say T is =<2
dict:
a->4, b->3, c->"Uncommon", d->"Uncommon"
Remap …Run Code Online (Sandbox Code Playgroud)