gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 02:24:34 25 4
gpt4 key购买 nike

我想将 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]

等等。

关于python - 在 pandas 列/索引上应用 NLTK 词干,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50764576/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com