Skip to main content
 首页 » 编程设计

python之在 pandas 列/索引上应用 NLTK 词干

2024年09月07日12yjmyzz

我想将 DataFrame 的列和索引限制为这样的内容

ps = PorterStemmer() 
df_dic = pd.read_csv('inquirerbasic_clean.csv', sep=';', index_col=0).T 
print(type(df_dic))  # pandas.core.frame.DataFrame 
df_dic.index = ps.stem(df_dic.index.str.lower()) 
df_dic.columns = ps.stem(df_dic.columns.str.lower()) 

我得到这个错误:

  File "<ipython-input-18-0156717e5956>", line 5, in <module> 
    df_dic.index = ps.stem(df_dic.index.str.lower()) 
 
  File "/usr/lib/python3.6/site-packages/nltk/stem/porter.py", line 632, in stem 
    stem = self.stem_word(word.lower(), 0, len(word) - 1) 
 
AttributeError: 'Index' object has no attribute 'lower' 

此外,如果我将索引转换为列表:

ps.stem(list(df_dic.index.str.lower())) 

我收到一条等效的错误消息:

  File "/usr/lib/python3.6/site-packages/nltk/stem/porter.py", line 632, in stem 
    stem = self.stem_word(word.lower(), 0, len(word) - 1) 
 
AttributeError: 'list' object has no attribute 'lower' 

那么,我该如何阻止它们呢?

请您参考如下方法:

这些适用于字符串,而不是列表,因此使用 map 应用 ps.stem。

df_dic.index = df_dic.index.str.lower().map(ps.stem) 
df_dic.columns = df_dic.columns.str.lower().map(ps.stem) 

如果你不满意(无论出于何种原因),请使用列表理解:

df_dic.index = [ps.stem(v.lower()) for v in df_dic.index] 

等等。