【问题标题】:Pandas multi-index count occurrencesPandas 多索引计数出现
【发布时间】:2017-05-02 04:29:56
【问题描述】:

我有一个带有 MultiIndexing 的 Pandas DataFrame

(Index col 1) (Index col 2) (Data col 1) ....
A               a            word1
                a            word2
                b            word3
B               a            word4
                c            word5

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

期望的输出: 一个 2 乙 1 ..等

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

【问题讨论】:

  • 试试df.groupby(level=[0,1]).size()
  • @EdChum 做到了,谢谢!

标签: python pandas jupyter-notebook


【解决方案1】:

您可以使用 index.get_level_values 将索引级别与另一列组合

 grouped = df.groupby([df.index.get_level_values(0),'Num']).size()

【讨论】:

    【解决方案2】:

    您可以在感兴趣的索引上 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
    

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

    【讨论】:

    • Ipython/Jupyter?还是 Spyder?
    • @MohammadYusufGhazi 您对此有何评论?
    • In[4] 和 Out[4] 表示法。
    • ipython/jupyter
    猜你喜欢
    • 2014-09-27
    • 1970-01-01
    • 2020-10-22
    • 2021-08-25
    • 2020-08-20
    • 1970-01-01
    • 2019-12-26
    • 2020-10-17
    • 1970-01-01
    相关资源
    最近更新 更多