在作为列表列表的数据帧的每一行中应用TfidfVectorizer

时间:2018-11-08 10:04:46

标签: python list dataframe tfidfvectorizer

我有一个包含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']

1 个答案:

答案 0 :(得分: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)