首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在每一行数据中应用TfidfVectorizer,这是一个列表列表

在每一行数据中应用TfidfVectorizer,这是一个列表列表
EN

Stack Overflow用户
提问于 2018-11-08 10:04:45
回答 1查看 1.3K关注 0票数 1

我有一个包含2列的熊猫数据,我想在其中一个列中使用text-classificationsklearn TfidfVectorizer。然而,这一列是列表的列表,TFIDF希望原始输入作为文本。在这个问题中,它们提供了一个解决方案,以防我们只有一个列表,但我想问一下,如何才能在我的dataframe的每一行中应用这个函数,这一行包含一个列表列表。提前谢谢你。

代码语言:javascript
复制
Input:

0    [[this, is, the], [first, row], [of, dataframe]]
1    [[that, is, the], [second], [row, of, dataframe]]
2    [[etc], [etc, etc]]

想要的产出:

代码语言:javascript
复制
0    ['this is the', 'first row', 'of dataframe']
1    ['that is the', 'second', 'row of dataframe']
2    ['etc', 'etc etc']
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-11-08 10:19:35

你可以用应用

代码语言:javascript
复制
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'])

输出

代码语言:javascript
复制
0     [this is the, first row, of dataframe]
1    [that is the, second, row of dataframe]
Name: result, dtype: object

此外,如果您想结合上面的函数应用矢量器,您可以这样做:

代码语言:javascript
复制
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)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53205421

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档