简体   繁体   English

Python熊猫按两列分组

[英]Python pandas group by two columns

I have a pandas dataframe: 我有一个熊猫数据框:

       code   type
index  
  312   11     21
  312   11     41 
  312   11     21
  313   23     22
  313   11     21
  ...   ...    

So I need to group it by count of pairs 'code' and 'type' columns for each index item: 因此,我需要根据每个索引项的“代码”和“类型”列对的计数将其分组:

        11_21   11_41  23_22
index  
  312       2      1      0
  313       1      0      1
  ...   ...   

How implement it with python and pandas? 如何用python和pandas实现它?

Here's one way using pd.crosstab and then rename column names, using levels information. 这是使用pd.crosstab然后使用级别信息重命名列名称的一种方法。

In [136]: dff = pd.crosstab(df['index'], [df['code'], df['type']])

In [137]: dff
Out[137]:
code  11    23
type  21 41 22
index
312    2  1  0
313    1  0  1

In [138]: dff.columns = ['%s_%s' % c for c in dff.columns]

In [139]: dff
Out[139]:
       11_21  11_41  23_22
index
312        2      1      0
313        1      0      1

Alternatively, less elegantly, create another column and use crosstab. 或者,不太优雅地创建另一个列并使用交叉表。

In [140]: df['ct'] = df.code.astype(str) + '_' + df.type.astype(str)

In [141]: df
Out[141]:
   index  code  type     ct
0    312    11    21  11_21
1    312    11    41  11_41
2    312    11    21  11_21
3    313    23    22  23_22
4    313    11    21  11_21

In [142]: pd.crosstab(df['index'], df['ct'])
Out[142]:
ct     11_21  11_41  23_22
index
312        2      1      0
313        1      0      1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM