【问题标题】:Apply TfidfVectorizer in every row of dataframe that is a list of lists在作为列表列表的数据帧的每一行中应用 TfidfVectorizer
【发布时间】:2019-04-11 19:47:35
【问题描述】:

我有一个包含 2 列的 pandas 数据框,我想在其中之一中使用 sklearn TfidfVectorizer 进行 文本分类。但是,此列是列表列表,并且 TFIDF 想要将原始输入作为文本。在this question 中,他们提供了一个解决方案,以防我们只有一个列表列表,但我想问一下如何在我的数据框的每一行中应用这个函数,哪一行包含一个列表列表。提前谢谢你。

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']

【问题讨论】:

  • 您能添加一些示例输入吗?
  • 我更新了丹尼尔的问题

标签: python list dataframe tfidfvectorizer


【解决方案1】:

你可以使用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)

【讨论】:

  • 这个结果正常吗? [<10x17 sparse matrix of type '<class 'numpy.float64'>' ` 以压缩稀疏行格式存储 19 个元素>` <644x855 sparse matrix of type '<class 'numpy.float64'>' with 3092 stored elements in Compressed Sparse Row format>
  • @joasa 那是因为 vectorizer.fit_transform 返回一个稀疏矩阵,通过将其应用于每个单元格,您会得到一列稀疏矩阵。
猜你喜欢
  • 2015-09-09
  • 1970-01-01
  • 1970-01-01
  • 2011-06-13
  • 2021-09-19
  • 1970-01-01
  • 1970-01-01
  • 2020-05-08
  • 1970-01-01
相关资源
最近更新 更多