情感分析中的一个常见任务是获取Pandas数据帧单元格中的单词计数,并在此基础上创建一个新列。我该怎么做?
发布于 2017-09-26 14:22:00
假设您有一个使用
df = pandas.read_csv('dataset.csv')
然后,通过执行以下操作,添加一个新列,其中包含单词count:
df['new_column'] = df.columnToCount.apply(lambda x: len(str(x).split(' ')))
请记住,由于你是在新单词上分裂,所以分裂中的空格是很重要的。在执行此操作之前,您可能希望删除标点符号或数字,并将其降为小写。
df = df.apply(lambda x: x.astype(str).str.lower())
df = df.replace('\d+', '', regex = True)
df = df.replace('[^\w\s\+]', '', regex = True)
发布于 2018-07-13 12:54:18
假设一个包含n个单词的句子中有n-1空格,那么还有另一个解决方案:
df['new_column'] = df['count_column'].str.count(' ') + 1
这个解决方案可能更快,因为它不会将每个字符串拆分成一个列表。
如果count_column
包含空字符串,则需要对结果进行调整(请参阅下面的注释):
df['new_column'] = np.where(df['count_column'] == '', 0, df['new_column'])
发布于 2021-01-16 17:17:13
对于dataframe df,从所选列中删除标点符号:
string_text = df['reviews'].str
df['reviews'] = string_text.translate(str.maketrans('', '', string.punctuation))
得到单词计数:
df['review_word_count'] = df['reviews'].apply(word_tokenize).tolist()
df['review_word_count'] = df['review_word_count'].apply(len)
使用新列写入CSV:
df.to_csv('./data/dataset.csv')
https://stackoverflow.com/questions/46429033
复制相似问题