Python 基于列值和其他列更新单元格

Python 基于列值和其他列更新单元格,python,pandas,apply,Python,Pandas,Apply,我希望根据一列中的值更新多个列;这对于循环来说很容易,但对于我的应用程序来说,当有许多列和许多行时,所需的时间太长。获得每个字母所需计数的最优雅方法是什么 期望输出: Things count_A count_B count_C count_D ['A','B','C'] 1 1 1 0 ['A','A','A'] 3 0 0

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

期望输出:

   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
选项1
应用
+
值\u计数

s = pd.Series([list('ABC'), list('AAA'), list('BA'), list('DD')], name='Things')

pd.concat([s, s.apply(lambda x: pd.Series(x).value_counts()).fillna(0)], axis=1)

选项2
使用
pd.DataFrame(s.tolist())
+
stack
/
groupby
/
unstack

pd.concat([s,
           pd.DataFrame(s.tolist()).stack() \
             .groupby(level=0).value_counts() \
             .unstack(fill_value=0)],
          axis=1)

最优雅的绝对是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之前的回复(否则看起来很好!)

100圈,最佳3圈:每圈3.27毫秒

我的答覆是:

pd.DataFrame(data=cv.fit_transform(things).toarray(), columns=["count_"+n for n in cv.get_feature_names()], index=raw)
1000个循环,最好3个:每个循环1.08毫秒

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

pd.DataFrame(data=cv.fit_transform(things).toarray(), columns=["count_"+n for n in cv.get_feature_names()], index=raw)