如何在Pandas中按指定位置的特定字母筛选DataFrame?
解决方法:筛选指定位置含特定字母的单词
修改后的完整代码
import pandas as pd # 读取CSV数据(路径用/或\\避免转义问题) d1 = pd.read_csv("skribble/Skribbl-words.csv") keyword_len = int(input('输入单词总长度: ')) hint1 = input('输入提示1的字母: ') hint1_pos = input('输入提示1的位置: ') hint2 = input('输入提示2的字母: ') hint2_pos = input('输入提示2的位置: ') # 1. 先筛选长度匹配的单词 plausiblewords = d1.loc[d1['count'] == keyword_len] # 2. 处理位置输入(转成0-based索引,用户输入通常从1开始计数) if hint1_pos.strip(): hint1_pos_idx = int(hint1_pos) - 1 # 筛选指定位置含hint1的单词,统一转小写避免大小写不匹配 plausiblewords = plausiblewords.loc[ plausiblewords['word'].str.lower().str.get(hint1_pos_idx) == hint1.lower() ] if hint2_pos.strip(): hint2_pos_idx = int(hint2_pos) - 1 plausiblewords = plausiblewords.loc[ plausiblewords['word'].str.lower().str.get(hint2_pos_idx) == hint2.lower() ] # 输出结果:可选择打印DataFrame或转成列表 print("符合条件的单词:") print(plausiblewords) # 如需转成列表: # print(plausiblewords['word'].tolist())
关键逻辑说明
- 位置索引转换:
日常表述的“第1个字母”对应Python字符串的0号索引,所以要把用户输入的位置减1,确保取到正确的字符位置。 - pandas字符串方法
str.get():
这是批量处理字符串列的核心方法,series.str.get(idx)会对列中每个字符串提取第idx个字符,完美适配“指定位置字母”的筛选需求。 - 大小写兼容处理:
统一把单词和输入的提示字母转成小写,避免CSV中单词大小写不一致导致的匹配失败(比如CSV里是"Apple",用户输入"a"也能匹配)。 - 空提示容错:
加入strip()判断,如果用户没输入提示(直接回车),就跳过该筛选条件,让代码更灵活。
内容的提问来源于stack exchange,提问作者Binitpyro
相关产品推荐
相关产品推荐

