我正在用编程的方式尝试bin分类列—有没有想过如何在不手动硬编码该列中的每个值的情况下实现这一点
基本上,我想要的是一个函数,它将所有值统计到80%[保留城市名称不变],并用单词“Other”替换剩余的20%城市名称
IE:如果前17个城市名称占该列的80%,请保持城市名称不变,否则返回'other'。你知道吗
例如:
0 Brighton
1 Yokohama
2 Levin
3 Melbourne
4 Coffeyville
5 Whakatane
6 Melbourne
7 Melbourne
8 Levin
9 Ashburn
10 Te Awamutu
11 Bishkek
12 Melbourne
13 Whanganui
14 Coffeyville
15 New York
16 Brisbane
17 Greymouth
18 Brisbane
19 Chuo City
20 Accra
21 Levin
22 Waiouru
23 Brisbane
24 New York
25 Chuo City
26 Lucerne
27 Whanganui
28 Los Angeles
29 Melbourne
df['city'].head(30).value_counts(ascending=False, normalize=True)*100
Melbourne 16.666667
Levin 10.000000
Brisbane 10.000000
Whanganui 6.666667
Coffeyville 6.666667
New York 6.666667
Chuo City 6.666667
Waiouru 3.333333
Greymouth 3.333333
Te Awamutu 3.333333
Bishkek 3.333333
Lucerne 3.333333
Ashburn 3.333333
Yokohama 3.333333
Whakatane 3.333333
Accra 3.333333
Brighton 3.333333
Los Angeles 3.333333
从Ashburn down-应该重命名为“other”
我试过以下方法,这是一个开始,但并不完全是我想要的:
city_map = dict(df['city'].value_counts(ascending=False, normalize=True)*100)
df['city_count']= df['city'].map(city_map)
def count(df):
if df["city_count"] > 10:
return "High"
elif df["city_count"] < 0:
return "Medium"
else:
return "Low"
df.apply(count, axis=1)
我不期待任何代码-只是一些指导从哪里开始或如何实现这一点的想法
我们可以在
city
上分组,得到每个城市的size
。我们用len
将这些值除以数据帧的长度,然后计算cumsum
。最后一步是检查从哪一点超过阈值,这样我们就可以用map
将布尔序列广播回您的数据帧。你知道吗旧方法
如果我理解正确,您需要用
.cumsum
计算一个累积和,并在它超过您设置的阈值时进行检查。你知道吗然后我们使用
np.where
有条件地填充City name
或Other
。你知道吗注意:此方法假定
Normalized
列按降序排序。你知道吗相关问题 更多 >
编程相关推荐