python - 在作为列表列表的数据帧的每一行中应用 TfidfVectorizer
问题描述
我有一个包含 2 列的 pandas 数据框,我想在其中之一中sklearn TfidfVectorizer
用于文本分类。但是,此列是列表列表,并且 TFIDF 想要将原始输入作为文本。在这个问题中,如果我们只有一个列表列表,他们提供了一个解决方案,但我想问一下如何在我的数据框的每一行中应用这个函数,哪一行包含一个列表列表。先感谢您。
Input:
0 [[this, is, the], [first, row], [of, dataframe]]
1 [[that, is, the], [second], [row, of, dataframe]]
2 [[etc], [etc, etc]]
想要的输出:
0 ['this is the', 'first row', 'of dataframe']
1 ['that is the', 'second', 'row of dataframe']
2 ['etc', 'etc etc']
解决方案
您可以使用apply:
import pandas as pd
df = pd.DataFrame(data=[[[['this', 'is', 'the'], ['first', 'row'], ['of', 'dataframe']]],
[[['that', 'is', 'the'], ['second'], ['row', 'of', 'dataframe']]]],
columns=['paragraphs'])
df['result'] = df['paragraphs'].apply(lambda xs: [' '.join(x) for x in xs])
print(df['result'])
输出
0 [this is the, first row, of dataframe]
1 [that is the, second, row of dataframe]
Name: result, dtype: object
此外,如果您想将矢量化器与上述函数结合使用,您可以执行以下操作:
def vectorize(xs, vectorizer=TfidfVectorizer(min_df=1, stop_words="english")):
text = [' '.join(x) for x in xs]
return vectorizer.fit_transform(text)
df['vectors'] = df['paragraphs'].apply(vectorize)
print(df['vectors'].values)
推荐阅读
- centos7 - 我正在尝试在 centos 7 上远程挂载文件系统
- asp.net - 在不登录用户的情况下更新 AWS Cognito 用户的自定义属性
- reactjs - 如何通过在 StencilJS 中滚动到顶部来在加载内容时保持滚动位置?
- css - 在 Chrome 中组合过滤器和 :hover 时出现奇怪的行为
- javascript - (Fullcalendar 4 VueJS) - 从 AM/PM 到 24H 的行时间格式
- c# - 如何关闭/处置 Nlog 的直布罗陀代理?
- jquery - 如何使用 Asp.Net Webform 和 Ajax 获得确认框?
- javascript - 尝试以“计数器”设置动画时返回错误值
- python - 使用 sqlalchemy 根据 python 列表更新数据库表
- python - 基于另一个参数向 argparse 添加参数的 Pythonic 方式