如何按指定条件拆分包含问答数据的Pandas DataFrame
Pandas 自定义规则DataFrame拆分实现
完整可运行代码
import pandas as pd # 定义拆分规则对应的词表 yn_list = ['Do','Does','Did','do','does','did','Am','Are','Is','Was','Were','am','are','is','was','were', 'Have','Has','Had','have','has','had','Will','Would','Shall','Should','Can','Could','May', 'Might','will','would','shall','should','can','could','may','might'] yn_negative_list = ["Don't","Doesn't","Didn't","don't","doesn't","didn't","Aren't","Isn't","aren't","isn't", "Wasn't","Weren't","wasn't","weren't","Haven't","Hasn't","Hadn't","haven't","hasn't", "hadn't","Won't","Wouldn't","won't","wouldn't","Shan't","shan't","Shouldn't","Can't", "Couldn't","shouldn't","can't","couldn't","may not","May not","Mightn't","mightn't"] wh_list = ['who','where','what','when','why','whom','which','whose','how'] # 合并为集合结构,大幅提升匹配效率 yn_all_set = set(yn_list + yn_negative_list) wh_set_lower = set(word.lower() for word in wh_list) # 转小写实现大小写不敏感匹配 def extract_first_word(text): # 清除文本首尾所有空白、换行符,避免首词提取错误 stripped = str(text).strip() if not stripped: return "" # 按连续空格分割,仅取第一个词,避免多空格导致的分割错误 return stripped.split(maxsplit=1)[0] # 对原DataFrame做预处理 df['first_word'] = df['Questions'].apply(extract_first_word) # 生成三个拆分用的布尔掩码 mask_df1 = df['first_word'].isin(yn_all_set) mask_df2 = df['first_word'].str.lower().isin(wh_set_lower) mask_df3 = df['Questions'].str.strip().str.endswith('.') # 应用掩码拆分,移除辅助列,重置索引 df1 = df[mask_df1].drop(columns=['first_word']).reset_index(drop=True) df2 = df[mask_df2].drop(columns=['first_word']).reset_index(drop=True) df3 = df[mask_df3].drop(columns=['first_word']).reset_index(drop=True)
关键逻辑说明
- 首词提取阶段用
strip()清除文本首尾的空白、换行符,适配示例中存在的空行、文本前后多余空格的场景,避免取到空字符串或者错误的字符作为首词 - 匹配逻辑用集合替代列表存储规则词,将
isin的查找效率从O(n)降低到O(1),适配百万行级别的大数据量场景 - wh词的匹配统一转小写处理,解决规则列表为小写、实际问句首词是大写开头(比如示例中的
Where、What)导致的漏判问题 - 结尾判断前先对文本做
strip()处理,避免文本末尾有多余空格、制表符导致的句号匹配失败 - 三个原始判定条件未做互斥限制,如果需要保证三个拆分后的DataFrame内容完全无重叠,可以在生成掩码时增加互斥排除逻辑,例:
mask_df3 = df['Questions'].str.strip().str.endswith('.') & ~mask_df1 & ~mask_df2,避免同一行被多个DataFrame收录
示例数据匹配结果
针对提供的示例数据,拆分后的三个DataFrame内容为:
df1:共2行,对应Is he a scientist? / No、Did he stole my money? / Yes两个Yes/No型问句df2:共2行,对应Where is Amazon? / Brazil、What does your father do? / Business两个wh引导的特殊问句df3:共2行,对应He is a great player. / I don't think so.、She is my girlfriend. / I too agree.两个以句号结尾的陈述句
内容的提问来源于stack exchange,提问作者Rikky Bhai
相关产品推荐
相关产品推荐

