Python 蟒蛇熊猫计数

Python 蟒蛇熊猫计数,python,pandas,dataframe,count,Python,Pandas,Dataframe,Count,我喜欢建立计数工具 我曾经使用excel中的COUNTIF函数=COUNTIF($L$2:$L$3850,“AAA”)。但是,我不确定python中是否有类似的函数 这是我的数据帧 # 2015 2016 2017 # 0 AAA AA AA # 1 AA AA A # 2 AA A A 我想这样计算这个数据帧: # 2015 2016 2017 # AAA 1 0

我喜欢建立计数工具

我曾经使用excel中的
COUNTIF
函数
=COUNTIF($L$2:$L$3850,“AAA”)
。但是,我不确定python中是否有类似的函数

这是我的数据帧

#        2015  2016  2017
#  0      AAA   AA    AA
#  1      AA    AA    A
#  2      AA    A     A
我想这样计算这个数据帧:

#        2015  2016  2017
#  AAA    1     0     0
#  AA     2     2     1
#  A      0     1     2 
如何启动代码?有什么建议吗


提前谢谢

使用
交叉选项卡

df.stack().pipe(lambda s: pd.crosstab(s, s.index.get_level_values(1)))

col_0  2015  2016  2017
row_0                  
A         0     1     2
AA        2     2     1
AAA       1     0     0

使用
get_假人

pd.get_dummies(df.values.ravel()).T.dot(
    pd.get_dummies(df.columns.repeat(len(df)))
)

     2015  2016  2017
A       0     1     2
AA      2     2     1
AAA     1     0     0

应用
值\u计数

df.apply(pd.value_counts).fillna(0).astype(int)
Out[203]: 
     2015  2016  2017
A       0     1     2
AA      2     2     1
AAA     1     0     0

另外:
df.apply(pd.value_counts).fillna(0,downcast='infer')
@piRSquared哇,从没听说过
downcast
,非常感谢您,先生,欢迎您(-:但要注意潜在性能@JakeHan yw~:-)