如果该类别的值计数小于 10,我想用“其他”替换熊猫数据框中的所有类别。
我正在尝试这样的事情。
df['variable'].where(df['variable'].apply(lambda x: x.map(x.value_counts()))<=10, "other")
Run Code Online (Sandbox Code Playgroud)
但我收到以下错误:
AttributeError: 'str' object has no attribute 'map'
Run Code Online (Sandbox Code Playgroud)
您可以通过计算每个值的计数pd.Series.value_counts,然后识别低于上限的计数。pd.DataFrame.loc然后与布尔索引一起使用:
counts = df['variable'].value_counts()
idx = counts[counts.lt(10)].index
df.loc[df['variable'].isin(idx), 'A'] = 'Others'
Run Code Online (Sandbox Code Playgroud)
一般来说,您应该避免使用apply+ lambda,因为它是非矢量化的,只不过是一个薄薄的循环。这是一个包含数字数据和添加列来演示逻辑的工作示例:
np.random.seed(0)
arr = np.random.randint(0, 12, 100)
df = pd.DataFrame({'A': arr, 'B': arr})
counts = df['A'].value_counts()
idx = counts[counts.lt(10)].index
df['counts'] = df['A'].map(counts)
df.loc[df['A'].isin(idx), 'B'] = -1
print(df)
A B counts
0 5 -1 9
1 0 -1 9
2 3 3 14
3 11 -1 5
4 3 3 14
5 7 7 10
6 9 -1 9
7 3 3 14
8 5 -1 9
9 2 -1 5
10 4 4 13
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1385 次 |
| 最近记录: |