熊猫:按两列组合分组

时间:2018-08-01 22:11:50

标签: python pandas

我有如下数据。得分列是x对y的得分(相当于y对x)。

from collections import Counter
import pandas as pd

d = pd.DataFrame([('a','b',1), ('a','c', 2), ('b','a',3), ('b','a',3)], 
                 columns=['x', 'y', 'score'])

    x   y   score
0   a   b   1
1   a   c   2
2   b   a   3
3   b   a   3

我想评估每种组合的得分计数,因此('a'vs'b)和('b'vs'a')应该分组在一起,即

        score
x   y   
a   b   {1: 1, 3: 2}
    c   {2: 1}

但是,如果我执行d.groupby(['x', 'y']).agg(Counter),('a','b')和('b','a')不会合并在一起。有办法解决吗?谢谢!

        score
x   y   
a   b   {1: 1}
    c   {2: 1}
b   a   {3: 2}

3 个答案:

答案 0 :(得分:1)

如果您不关心订单,那么可以在两列上使用=IF(ISERROR(INDEX(C2:C6,MATCH(F2,C2:C6,0)))=TRUE,"n","y"),然后申请sort

groupby

答案 1 :(得分:1)

您还可以groupby使用frozensetx的总计y,然后使用agg

Counter

如果您想要from collections import Counter df.groupby(df[['x', 'y']].agg(frozenset, 1)).score.agg(Counter) (b, a) {1: 1, 3: 2} (a, c) {2: 1}

dataframe

答案 2 :(得分:1)

IIUC

d[['x','y']]=np.sort(d[['x','y']],1)
pd.crosstab([d.x,d.y],d.score)
Out[94]: 
score  1  2  3
x y           
a b    1  0  2
  c    0  1  0
相关问题