【发布时间】:2021-07-26 21:51:58
【问题描述】:
使用 Python 和 Pandas,我正在寻求编写一个脚本,该脚本从 text 列中获取数据,使用 textstat 模块评估该文本,然后将结果写回 word_countcolumn 下的 csv .
这是csv的结构:
user_id text text_number word_count
0 10 test text A text_0 NaN
1 11 NaN NaN NaN
2 12 NaN NaN NaN
3 13 NaN NaN NaN
4 14 NaN NaN NaN
5 15 test text B text_1 NaN
这是我尝试将 text 列循环到 textstat 的代码:
df = pd.read_csv("texts.csv").fillna('')
text_data = df["text"]
length1 = len(text_data)
for x in range(length1):
(text_data[x])
#this is the textstat word count operation
word_count = textstat.lexicon_count(text_data, removepunct=True)
output_df = pd.DataFrame({"word_count":[word_count]})
output_df.to_csv('texts.csv', mode="a", header=False, index=False)
但是,我收到此错误:
TypeError: 'Series' objects are mutable, thus they cannot be hashed
关于如何进行的任何建议?感谢所有帮助。
【问题讨论】:
-
您是否可能打算传递字符串
text_data[x]而不是系列?word_count = textstat.lexicon_count(text_data[x], removepunct=True) -
您希望如何处理 NaN 值?
-
非常感谢 - 它看起来不像。运行该代码产生了这个错误:~TypeError: expected string or bytes-like object~
-
对。因为您在
float64的列中有 NaN。那么您希望如何处理这些问题? -
很好 - 我编辑了上面的代码以包含
fillna('')。使用test_data[x]再次运行代码是成功的,尽管它把它放在user_id列而不是word_count中。我应该将header值更改为True?