最优雅的绝对是 sklearn 的 CountVectorizer。
我将首先向您展示它是如何工作的,然后我将在一行中完成所有操作,这样您就可以看到它是多么优雅。
首先,我们将逐步进行:
让我们创建一些数据
raw = ['ABC', 'AAA', 'BA', 'DD']
things = [list(s) for s in raw]
然后读入一些包并初始化计数向量化器
from sklearn.feature_extraction.text import CountVectorizer
import pandas as pd
cv = CountVectorizer(tokenizer=lambda doc: doc, lowercase=False)
接下来我们生成一个计数矩阵
matrix = cv.fit_transform(things)
names = ["count_"+n for n in cv.get_feature_names()]
并另存为数据框
df = pd.DataFrame(data=matrix.toarray(), columns=names, index=raw)
生成这样的数据框:
count_A count_B count_C count_D
ABC 1 1 1 0
AAA 3 0 0 0
BA 1 1 0 0
DD 0 0 0 2
优雅版:
以上所有内容都在一行中
df = pd.DataFrame(data=cv.fit_transform(things).toarray(), columns=["count_"+n for n in cv.get_feature_names()], index=raw)
Timing:
您提到您正在使用相当大的数据集,因此我使用 %%timeit 函数来给出时间估计。
@piRSquared 之前的回复(否则看起来非常好!)
pd.concat([s, s.apply(lambda x: pd.Series(x).value_counts()).fillna(0)], axis=1)
100 loops, best of 3: 3.27 ms per loop
我的答案:
pd.DataFrame(data=cv.fit_transform(things).toarray(), columns=["count_"+n for n in cv.get_feature_names()], index=raw)
1000 loops, best of 3: 1.08 ms per loop
根据我的测试,计数向量化器大约快 3 倍。