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

Python中如何使用contains或in函数筛选已选选项完成计数统计

Pandas多选问卷选项计数实现方案

原有代码问题说明

df['options'].isin(options)返回全False的原因是:isin方法仅对单元格做整值精确匹配,而你的options列存储的是逗号拼接的多选项字符串(如Apple, Banana),不是单个选项值,因此无法匹配到预设的单个选项列表。

完整实现步骤

1. 基础逻辑实现

先拆分每行的选项字符串为独立选项列表,再分别统计固定选项、Other类的计数即可,代码如下:

import pandas as pd

# 构造示例数据集(替换为你的实际数据即可)
df = pd.DataFrame({
    'ID': [1, 2, 3, 4],
    'options': ['Apple, Banana', 'Apple', 'Apple, Banana, Pear, Orange', 'Orange']
})

# 预设的固定选项列表
fixed_options = ['Apple', 'Banana', 'Pear']

# 将每行逗号拼接的选项拆分为去空格后的选项列表
df['option_list'] = df['options'].str.split(',').apply(lambda x: [item.strip() for item in x])

# 统计各固定选项的选择次数
count_res = {}
for opt in fixed_options:
    count_res[opt] = df['option_list'].apply(lambda opt_list: opt in opt_list).sum()

# 统计Other类计数:只要该行存在任意不在固定选项里的内容,即计入1次Other
count_res['Other'] = df['option_list'].apply(lambda opt_list: any(item not in fixed_options for item in opt_list)).sum()

运行后count_res的输出完全匹配预期结果:

{'Apple': 3, 'Banana': 2, 'Pear': 1, 'Other': 2}

2. 更简洁的实现方式

可以直接用pandas内置的字符串哑变量方法实现,无需手动拆分列表:

# 按分隔符拆分直接生成多热编码表
dummy_df = df['options'].str.get_dummies(sep=', ')

# 固定选项直接按列求和得到计数
count_res = dummy_df[fixed_options].sum().to_dict()

# Other计数:排除固定选项列后,行求和大于0即代表该行选了非预设选项
count_res['Other'] = (dummy_df.drop(columns=fixed_options).sum(axis=1) > 0).sum()

注意事项

  • 上述代码中Other的计数规则是单用户只要选了任意非预设选项,仅计数1次,和示例预期逻辑一致;如果需要统计所有非预设选项的总选择次数,直接对非固定选项列全局求和即可。
  • 拆分选项时注意处理分隔符后的空格,避免因为空格存在导致匹配失败(如把 Banana识别为独立于Banana的选项)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.01 20:03:39