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

基于文本响应的Python用户访谈数据过滤优化方案问询

高效筛选Departmental PM访谈数据的优化方案

原代码的核心问题是循环中使用df.append()拼接DataFrame,这类操作会频繁复制数据,在数据量较大时效率偏低(即便只有35个工作表,concat也比多次append更优雅高效)。以下是优化后的实现方案:

优化代码

import pandas as pd

# 提前定义列名映射,避免重复编写
COLUMN_MAPPING = {
    'Unnamed: 1': 'Questions',
    'INTERVIEW QUESTIONS': 'Question Topics',
    'INTERVIEW RESPONSES': 'Interview Responses'
}

# 用列表存储符合条件的DataFrame,替代循环内append
departmental_dfs = []

for sheet in sheets:
    # 读取工作表数据
    df = pd.read_excel(excel_file, sheet_name=sheet)
    # 批量重命名列
    df = df.rename(columns=COLUMN_MAPPING)
    # 统一转换响应列为字符串类型
    df['Interview Responses'] = df['Interview Responses'].astype(str)
    
    # 检查第2行(索引1)的角色是否为Departmental PM
    if df['Interview Responses'].iloc[1] == 'Departmental PM':
        # 链式执行文本预处理与情感分析
        df['Clean_Responses'] = df['Interview Responses'].apply(finalpreprocess).str.replace('^[0-9]', '', regex=True)
        df['Sentiment_Rating'] = df['Clean_Responses'].apply(sentiment_score)
        # 将符合条件的数据集加入列表
        departmental_dfs.append(df)

# 一次性拼接所有符合条件的DataFrame
df_departmental = pd.concat(departmental_dfs, ignore_index=True)
# 输出筛选结果数量
print(f"共筛选出 {len(departmental_dfs)} 位Departmental PM受访者")

关键优化点

  • 替换循环内append:用列表收集DataFrame后一次性concat,减少内存碎片和重复的数据复制操作,效率提升明显。
  • 常量复用:把列名映射做成字典,代码更整洁,后续修改列名只需调整字典即可。
  • 简化链式操作:将apply和str.replace合并为链式调用,减少中间变量的冗余。
  • 明确行索引:用iloc[1]替代loc[1],避免因索引混乱导致的错误(假设角色回答固定在第2行)。
  • 冗余变量移除:直接通过列表长度统计符合条件的数量,逻辑更清晰。

扩展建议(针对任职时长筛选需求)

如果后续要筛选任职时长(如>18个月/<18个月),可以在判断逻辑中加入时长解析:

# 假设任职时长在第4行(索引3),格式为"X years Y months"或"Z months"
def parse_tenure(tenure_str):
    total_months = 0
    if 'year' in tenure_str.lower():
        # 提取年数并转换为月
        years = int(tenure_str.split('year')[0].strip())
        total_months += years * 12
    if 'month' in tenure_str.lower():
        # 提取月数
        month_part = tenure_str.split('month')[0].split()[-1]
        total_months += int(month_part)
    return total_months

# 在循环中加入时长筛选
tenure_months = parse_tenure(df['Interview Responses'].iloc[3])
if tenure_months > 18:
    # 执行后续预处理与情感分析逻辑
    ...

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 09:53:17