You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Pandas筛选C1列值出现次数≤2的行并添加type列

问题解决:DataFrame按频次标记列并提取低频值列表

原始数据

import pandas as pd

# 构造目标原始DataFrame
df = pd.DataFrame({
    'C1': ['a.', 'd.', 'd.', 'd.', 'b.', 'b.', 'c.', 'a.', 'b.'],
    'C2': [2, 8, 5, 5, 3, 4, 5, 6, 7]
})

需求说明

  1. 对C1列中出现次数≤2的行,新增type列并赋值为low;
  2. 其余行的type列保留C1原始值(去除末尾的点);
  3. 提取所有被标记为low的C1值列表(示例结果为['a','c'])。

实现代码

# 计算C1列各值的出现频次
c1_freq = df['C1'].value_counts()

# 生成type列
df['type'] = df['C1'].apply(lambda x: 'low' if c1_freq[x] <= 2 else x[:-1])

# 获取低频值列表
low_c1_values = df[df['type'] == 'low']['C1'].str[:-1].unique().tolist()

结果验证

处理后的DataFrame如下:

C1  C2 type
0  a.   2  low
1  d.   8    d
2  d.   5    d
3  d.   5    d
4  b.   3    b
5  b.   4    b
6  c.   5  low
7  a.   6  low
8  b.   7    b

提取的低频值列表为:['a', 'c']

内容的提问来源于stack exchange,提问作者Cranjis

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 07:40:24