Skip to main content
 首页 » 编程设计

python之在 Pandas 的特定位置获取元音单元格中的单词

2025年05月04日24mengfanrong

我有一个包含以下列的 Pandas 数据框 词缀、单词、意义和意义。现在,如果我想获取 word 列中的所有条目,其倒数第四个字符是 a。

下面的片段为我提供了答案

pd[(pd['affix'] == 'man') & (pd['word'].str[-4] == 'a' )  ] 

输出是

        affix   word        sense                  meaning 
9900    man     cameraman   who     # somebody who operates a [[movie]] [[camera]]... 
9901    man     cameraman   who     # {{l|en|cameraman}} {{gloss|somebody who oper... 

但是如果我想获取倒数第 4 个字符是元音的条目,则以下代码片段不起作用。任何帮助都有助于实现结果

  pd[(pd['affix'] == 'man') & (pd['word'].str[-4] in ['a','e','i','o','u'] )  ] 

显示的错误是

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). 

请您参考如下方法:

您可以匹配 str.match

pd[(pd['affix'] == 'man') & pd.str.match('.*[aeiou].{3}$') 

'.*[aeiou].{3}$' 是一个正则表达式,表示:

  • '.*' 匹配任意次数
  • '[aeiou]' 后跟括号中列表中的单个字符
  • '.{3}$' 后跟任意 3 个字符,然后是字符串的末尾。