簡體   English   中英

熊貓:由兩列組合而成

[英]Pandas: Group by combination of two columns

我的數據如下。 得分列是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}

如果你不關心訂單那么,可能你可以在兩列上使用sort ,apply, groupby

import pandas as pd
from collections import Counter

d = pd.DataFrame([('a','b',1), ('a','c', 2), ('b','a',3), ('b','a',3)], 
                 columns=['x', 'y', 'score'])
# Note: you can copy to other dataframe if you do not want to change original
d[['x', 'y']] = d[['x', 'y']].apply(sorted, axis=1) 
x = d.groupby(['x', 'y']).agg(Counter)
print(x)
# Result:
#             score
# x y              
# a b  {1: 1, 3: 2}
#   c        {2: 1}

您也可以groupby使用聚合frozensetxy ,然后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

.to_frame()

        score
(b, a)  {1: 1, 3: 2}
(a, c)  {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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM