【问题标题】:Number of unique pairs within one column - pandas一列中唯一对的数量 - 熊猫
【发布时间】:2018-11-06 05:59:45
【问题描述】:

我在为我的 pandas 数据框生成统计数据时遇到了一点问题。我的数据框看起来像这样(我省略了索引):

id    type  
1      A
2      B
3      A
1      B
3      B
2      C
4      B
4      C

重要的是,每个id 都分配了两个type 值,如上例所示。我想计算所有type 组合的出现次数(所以计算给定type 组合的唯一id 的数量),所以我想得到这样一个数据框:

type    count
A, B      2
A, C      0
B, C      2

我尝试在很多方面使用groupby,但没有成功。我可以使用for-loop 和一些代码行来做这种“计数”,但我相信必须有优雅和适当的(用python 术语)解决这个问题。

提前感谢任何提示。

【问题讨论】:

  • 所以你试图从所有types 中创建大小为 2 的组合,并计算其中有多少按 id 分组?我理解正确吗?

标签: python pandas pandas-groupby


【解决方案1】:

pd.value_countsitertools.combinations

from itertools import combinations

pd.value_counts(
    [(x, y) for _, d in df.groupby('id') for x, y in combinations(d.type, 2)]
)

(A, B)    2
(B, C)    2
dtype: int64

【讨论】:

    【解决方案2】:

    使用Countergroupby和默认构造函数

    from collections import Counter
    >>> pd.DataFrame(Counter([tuple(v.type.values) for _,v in df.groupby('id')]), index=['Count']).T
    
            Count
    A   B   2
    B   C   2
    

    【讨论】:

      【解决方案3】:

      使用GroupBy + applyvalue_counts

      from itertools import combinations
      
      def combs(types):
          return pd.Series(list(combinations(sorted(types), 2)))
      
      res = df.groupby('id')['type'].apply(combs).value_counts()
      
      print(res)
      
      (A, B)    2
      (B, C)    2
      Name: type, dtype: int64
      

      【讨论】:

        【解决方案4】:

        也许使用unique,注意只对一个id中的两个唯一值有用

        df.groupby('id').type.unique().apply(tuple).value_counts()
        Out[202]: 
        (A, B)    2
        (B, C)    2
        Name: type, dtype: int64
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-12-06
          • 2018-05-02
          • 2015-01-14
          • 2021-08-12
          • 2020-01-16
          • 1970-01-01
          • 2017-05-30
          • 1970-01-01
          相关资源
          最近更新 更多