将tfidf附加到pandas数据帧

lte*_*e__ 5 python tf-idf dataframe sklearn-pandas

我有以下pandas结构:

col1 col2 col3 text
1    1    0    meaningful text
5    9    7    trees
7    8    2    text
Run Code Online (Sandbox Code Playgroud)

我想用tfidf矢量化矢量化它.然而,这会返回一个解析矩阵,我实际上可以将其转换为密集矩阵mysparsematrix).toarray().但是,如何将此信息与标签一起添加到原始df中?所以目标看起来像:

col1 col2 col3 meaningful text trees
1    1    0    1          1    0
5    9    7    0          0    1
7    8    2    0          1    0
Run Code Online (Sandbox Code Playgroud)

更新:

即使重命名原始列,解决方案也会使连接错误: 在此输入图像描述 删除至少有一个NaN的列只会产生7行,即使我fillna(0)在开始使用它之前使用它.

Moh*_*OUI 14

您可以按以下步骤操作:

将数据加载到数据框中:

import pandas as pd

df = pd.read_table("/tmp/test.csv", sep="\s+")
print(df)
Run Code Online (Sandbox Code Playgroud)

输出:

   col1  col2  col3             text
0     1     1     0  meaningful text
1     5     9     7            trees
2     7     8     2             text
Run Code Online (Sandbox Code Playgroud)

text使用以下方法对列进行标记: sklearn.feature_extraction.text.TfidfVectorizer

from sklearn.feature_extraction.text import TfidfVectorizer

v = TfidfVectorizer()
x = v.fit_transform(df['text'])
Run Code Online (Sandbox Code Playgroud)

将标记化数据转换为数据帧:

df1 = pd.DataFrame(x.toarray(), columns=v.get_feature_names())
print(df1)
Run Code Online (Sandbox Code Playgroud)

输出:

   meaningful      text  trees
0    0.795961  0.605349    0.0
1    0.000000  0.000000    1.0
2    0.000000  1.000000    0.0
Run Code Online (Sandbox Code Playgroud)

将标记化数据框连接到orignal数据框:

res = pd.concat([df, df1], axis=1)
print(res)
Run Code Online (Sandbox Code Playgroud)

输出:

   col1  col2  col3             text  meaningful      text  trees
0     1     1     0  meaningful text    0.795961  0.605349    0.0
1     5     9     7            trees    0.000000  0.000000    1.0
2     7     8     2             text    0.000000  1.000000    0.0
Run Code Online (Sandbox Code Playgroud)

如果要删除列text,则需要在连接之前执行此操作:

df.drop('text', axis=1, inplace=True)
res = pd.concat([df, df1], axis=1)
print(res)
Run Code Online (Sandbox Code Playgroud)

输出:

   col1  col2  col3  meaningful      text  trees
0     1     1     0    0.795961  0.605349    0.0
1     5     9     7    0.000000  0.000000    1.0
2     7     8     2    0.000000  1.000000    0.0
Run Code Online (Sandbox Code Playgroud)

这是完整的代码:

import pandas as pd
from sklearn.feature_extraction.text import TfidfVectorizer

df = pd.read_table("/tmp/test.csv", sep="\s+")
v = TfidfVectorizer()
x = v.fit_transform(df['text'])

df1 = pd.DataFrame(x.toarray(), columns=v.get_feature_names())
df.drop('text', axis=1, inplace=True)
res = pd.concat([df, df1], axis=1)
Run Code Online (Sandbox Code Playgroud)

  • 这几乎可以工作,但是出了点问题......默认情况下,这会执行一个外连接,我最终得到 699 行而不是原来的 353 行,有很多 NaN 行......可能有什么问题? (3认同)