Pandas 多索引计数出现次数

Cel*_*ian 4 python pandas jupyter-notebook

我有一个带有多索引的 Pandas DataFrame

(Index col 1) (Index col 2) (Data col 1) ....
A               a            word1
                a            word2
                b            word3
B               a            word4
                c            word5
Run Code Online (Sandbox Code Playgroud)

现在我想计算索引列 1 和索引列 2 具有相同组合的所有行。我试过 df.value_counts(),它给出了错误“DataFrame 没有方法 value_counts()”。如果我使用 df.count(),我只能计算 level=0 或 level=1,不能同时计数(level 参数似乎不接受列表,即使我经常看到在 stackoverflow 上使用) .

期望输出:A a 2 A b 1 .. 等

[编辑]:好的,@EdChum 的评论解决了问题,但我仍然想知道为什么其他东西不起作用?具体来说:为什么 value_counts 似乎没有被定义,而它是最新 Pandas 的一部分?这与我使用 Jupyter Notebook 有什么关系吗?或者这些东西在 Pandas 版本之间变化很大吗?

EdC*_*ica 8

您可以groupby对感兴趣的索引并调用size返回唯一值的计数:

In [4]:
df.groupby(level=[0,1]).size()

Out[4]:
(Index col 1)  (Index col 2)
A              a                2
               b                1
B              a                1
               c                1
dtype: int64
Run Code Online (Sandbox Code Playgroud)

value_counts 是一个系列方法,它不是为 df 定义的,这就是它不起作用的原因