【问题标题】:Count unique combinations regardless of column order无论列顺序如何,计算唯一组合
【发布时间】:2021-05-19 22:28:44
【问题描述】:

我有两列类别,两列中都显示了相同的可能选项,并且我希望计算每个唯一组合的行数,而不管每行中类别的顺序(A 列或列B)。

示例数据框:

df1 = pd.DataFrame({'A':['dog','cat','mouse','bunny','cat','mouse','dog'],
                   'B':['cat','dog','dog','mouse','bunny','bunny','cat']})

看起来像:

----------------------------
index         A        B
0           dog       cat
1           cat       dog
2           mouse     dog
3           bunny     mouse
4           cat       bunny
5           mouse     bunny
6           dog       cat
-----------------------------

我希望结果看起来像:

--------------------------------------
index         A        B        count
0           dog       cat       3
1           bunny     mouse     2
2           mouse     dog       1
3           cat       bunny     1
--------------------------------------

我可以获得狗/猫与猫/狗分开计算的组合计数,但无论哪个类别首先,我都在努力获取计数。

【问题讨论】:

    标签: python pandas count combinations


    【解决方案1】:

    另一种解决方案,使用.groupby:

    x = (
        df1.groupby(df1.apply(lambda x: tuple(sorted(x)), axis=1))
        .agg(A=("A", "first"), B=("B", "first"), count=("B", "size"))
        .reset_index(drop=True)
    )
    print(x)
    

    打印:

           A      B  count
    0    cat  bunny      1
    1  bunny  mouse      2
    2    dog    cat      3
    3  mouse    dog      1
    

    【讨论】:

      【解决方案2】:

      尝试np.sort on axis=1 以获取同一列中的所有值,然后照常使用value_counts:

      import numpy as np
      import pandas as pd
      
      df1 = pd.DataFrame(
          {'A': ['dog', 'cat', 'mouse', 'bunny', 'cat', 'mouse', 'dog'],
           'B': ['cat', 'dog', 'dog', 'mouse', 'bunny', 'bunny', 'cat']})
      
      df2 = pd.DataFrame(np.sort(df1.values, axis=1), columns=df1.columns) \
          .value_counts().reset_index(name='counts')
      
      print(df2)
      

      df2:

             A      B  counts
      0    cat    dog       3
      1  bunny  mouse       2
      2  bunny    cat       1
      3    dog  mouse       1
      

      【讨论】:

      • 我收到错误“'DataFrame' 对象没有属性 'value_counts'”(完全按照上面的说明运行)
      • DataFrame.value_counts() 在 1.1.0 及更新版本中。
      猜你喜欢
      • 1970-01-01
      • 2013-11-30
      • 1970-01-01
      • 2012-07-10
      • 2017-07-28
      • 2016-06-05
      • 2016-06-28
      • 1970-01-01
      相关资源
      最近更新 更多