【问题标题】:How to create "others" category in Pandas Column efficiently? [duplicate]如何有效地在 Pandas Column 中创建“其他”类别? [复制]
【发布时间】:2019-01-12 14:20:05
【问题描述】:

我有一个pandas.DataFrame,如下所示:

print(df)

level   type

'xyz'     1
'abc'     2
'abc'     4
'abc'     3
'xyz'     3
'qwe'     2
'asd'     5
'poi'     1

我想用新值 others 替换 level 列中值计数小于 2 的所有值。

print(df['level'].value_counts())

abc    3
xyz    2
poi    1
qwe    1
asd    1

在上面的示例中,计数为 1 的类别即 qwe, asd, poi 应替换为 others

预期输出:

    level   type
0   xyz     1
1   abc     2
2   abc     4
3   abc     3
4   xyz     3
5   others  2
6   others  5
7   others  1

我尝试了什么

cats = []
x = dict(df['level'].value_counts())
for k,v in x.items():
    if v > 1:
        cats.append(k)

df['level'] = [j if j in cats else 'others' for i,j in df['level'].iteritems()]

上面的代码生成了预期的输出,但是速度太慢了。所以我在找 以获得更有效的解决方案。

【问题讨论】:

  • 标记的副本应该可以解决这个问题。 This answer 已更新,向您展示如何隔离计数为 1 的类别。

标签: python python-3.x pandas


【解决方案1】:

使用isin 创建布尔掩码和v 的过滤索引值,并通过loc 设置值:

v = df['level'].value_counts() == 1
df.loc[df['level'].isin(v.index[v]), 'level'] = 'others'
print (df)
    level  type
0     xyz     1
1     abc     2
2     abc     4
3     abc     3
4     xyz     3
5  others     2
6  others     5
7  others     1

详情

print (v.index[v])
Index(['qwe', 'asd', 'poi'], dtype='object')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-20
    • 1970-01-01
    • 2012-09-23
    • 2019-06-26
    • 1970-01-01
    • 2019-01-10
    相关资源
    最近更新 更多