将 tfidf 附加到 pandas 数据框

Append tfidf to pandas dataframe

我有以下 pandas 结构:

col1 col2 col3 text
1    1    0    meaningful text
5    9    7    trees
7    8    2    text

我想使用 tfidf 矢量化器对其进行矢量化。然而,这是 returns 一个解析矩阵,我实际上可以通过 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

更新:

解决方案即使在重命名原始列时也会导致连接错误: 删除至少有一个 NaN 的列只剩下 7 行,即使我在开始使用它之前使用 fillna(0)

您可以进行如下操作:

将数据加载到数据帧中:

import pandas as pd

df = pd.read_table("/tmp/test.csv", sep="\s+")
print(df)

输出:

   col1  col2  col3             text
0     1     1     0  meaningful text
1     5     9     7            trees
2     7     8     2             text

标记 text 列使用: sklearn.feature_extraction.text.TfidfVectorizer

from sklearn.feature_extraction.text import TfidfVectorizer

v = TfidfVectorizer()
x = v.fit_transform(df['text'])

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

df1 = pd.DataFrame(x.toarray(), columns=v.get_feature_names())
print(df1)

输出:

   meaningful      text  trees
0    0.795961  0.605349    0.0
1    0.000000  0.000000    1.0
2    0.000000  1.000000    0.0

将标记化数据帧连接到原始数据帧:

res = pd.concat([df, df1], axis=1)
print(res)

输出:

   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

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

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

输出:

   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

完整代码如下:

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)

您可以尝试以下方法 -

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

# create some data
col1 = np.asarray(np.random.choice(10,size=(10)))
col2 = np.asarray(np.random.choice(10,size=(10)))
col3 = np.asarray(np.random.choice(10,size=(10)))
text = ['Some models allow for specialized',
         'efficient parameter search strategies,',
         'outlined below. Two generic approaches',
         'to sampling search candidates are ',
         'provided in scikit-learn: for given values,',
         'GridSearchCV exhaustively considers all',
         'parameter combinations, while RandomizedSearchCV',
         'can sample a given number of candidates',
         ' from a parameter space with a specified distribution.',
         ' After describing these tools we detail best practice applicable to both approaches.']

# create a dataframe from the the created data
df = pd.DataFrame([col1,col2,col3,text]).T
# set column names
df.columns=['col1','col2','col3','text']

tfidf_vec = TfidfVectorizer()
tfidf_dense = tfidf_vec.fit_transform(df['text']).todense()
new_cols = tfidf_vec.get_feature_names()

# remove the text column as the word 'text' may exist in the words and you'll get an error
df = df.drop('text',axis=1)
# join the tfidf values to the existing dataframe
df = df.join(pd.DataFrame(tfidf_dense, columns=new_cols))

我想在接受的答案中添加一些信息。

在连接两个 DataFrame(即主 DataFrame 和 TF-IDF DataFrame)之前,请确保两个 DataFrame 之间的索引相似。例如,您可以使用 df.reset_index(drop=True, inplace=True) 来重置 DataFrame 索引。

否则,您的串联 DataFrame 将包含大量 NaN 行。看了评论,这可能是OP的经历。