我有一个包含2列的熊猫数据,我想在其中一个列中使用text-classification的sklearn TfidfVectorizer。然而,这一列是列表的列表,TFIDF希望原始输入作为文本。在这个问题中,它们提供了一个解决方案,以防我们只有一个列表,但我想问一下,如何才能在我的dataframe的每一行中应用这个函数,这一行包含一个列表列表。提前谢谢你。
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']发布于 2018-11-08 10:19:35
你可以用应用
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)https://stackoverflow.com/questions/53205421
复制相似问题