加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – 为每个索引应用pandas groupby

发布时间:2020-12-20 11:57:24 所属栏目:Python 来源:网络整理
导读:我有一个数据框,其中一个人的名字作为索引(可以有多个条目)和两列“X”和“Y”.列’X’和’Y’可以是A-C之间的任何字母. 例如: df = pd.DataFrame({'X' : ['A','B','A','C'],'Y' : ['B','C']},index = ['Bob','Bob','John','Mike']) 对于每个人(即索引),我
我有一个数据框,其中一个人的名字作为索引(可以有多个条目)和两列“X”和“Y”.列’X’和’Y’可以是A-C之间的任何字母.

例如:

df = pd.DataFrame({'X' : ['A','B','A','C'],'Y' : ['B','C']},index = ['Bob','Bob','John','Mike'])

对于每个人(即索引),我想得到列’X’和’Y’的每个唯一组合的出现次数(例如 – 对于Bob我有1个计数(‘A’,’B’)和1计数(‘B’,’A’)).

当我执行以下操作时:

df.loc['Bob'].groupby(['X','Y']).size()

我得到鲍勃的正确结果.如何在没有人的情况下为每个人这样做?
理想情况下,我会得到一个数据框,其中不同的人作为索引,列的“X”和“Y”的每个唯一组合作为列以及它在数据框中作为值出现的次数.

('A','A') ('A','B') ('A','C') ('B','A') ... ('C','C')
Bob     0         1         0         1             0
John    1         0         0         0             0
Mike    0         0         0         0             1

解决方法

我想你可以用:

#convert columns X and Y to tuples
df['tup'] = list(zip(df.X,df.Y))

#get size and reshape
df1 = df.reset_index().groupby(['index','tup']).size().unstack(fill_value=0)
print (df1)
tup    (A,A)  (A,B)  (B,A)  (C,C)
index                                
Bob         0       1       1       0
John        1       0       0       0
Mike        0       0       0       1

#get all unique combination
from  itertools import product
comb = list(product(df.X.unique(),df.Y.unique()))
print (comb)
[('A','B'),('A','A'),'C'),('B',('C','C')]

#reindex columns by this combination
print (df1.reindex(columns=comb,fill_value=0))
tup    (A,B)  (A,C)  (B,A)  (B,C)  (C,B)  (C,C)
index                                                                        
Bob         1       0       0       0       1       0       0       0       0
John        0       1       0       0       0       0       0       0       0
Mike        0       0       0       0       0       0       0       0       1

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读