根据列值和其他列更新熊猫细胞

this_is_david

我希望根据一列中的值更新许多列;这很容易使用循环,但是当有许多列和许多行时,这对于我的应用程序来说花费太长时间。获得每个字母所需的计数的最优雅的方法是什么?

所需输出:

   Things         count_A     count_B    count_C     count_D
['A','B','C']         1            1         1          0
['A','A','A']         3            0         0          0
['B','A']             1            1         0          0
['D','D']             0            0         0          2
里德

最优雅的绝对是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)

定时:

您提到您正在使用相当大的数据集,因此我使用%% 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

根据我的测试,CountVectorizer的速度大约快3倍。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章