• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

python中pandas对多列进行分组统计的实现

python 搞代码 4年前 (2022-01-07) 20次浏览 已收录 0个评论

分组统计在很多时候都需要用到,可以实现很多数据库函数的功能。本文主要介绍了python中pandas对多列进行分组统计的实现,感兴趣的可以了解一下

使用groupby([ ]).size()统计的结果,值相同的字段值会不显示

如上图所示,第一个空着的行是982499 7 3388 1,因为此行与前面一行的这两个字段值是一样的,所以不显示。第二个空着的行是390192 22 4278 1,因为此行与前面一行的第一个字段值是一样的,所以不显示。这样的展示方式更直观,但对于刚用的人,可能会让其以为是缺失值。
来源gao($daima.com搞@代@#码网

如果还不明白可以看下面的全部数据及操作。

 import pandas as pd res6 = pd.read_csv('test.csv') res6.shape 
 (12, 3)
 res6.columns
 Index(['user_id', 'cate', 'shop_id'], dtype='object')
 res6.info()
  RangeIndex: 12 entries, 0 to 11 Data columns (total 3 columns): user_id    12 non-null int64 cate       12 non-null int64 shop_id    12 non-null int64 dtypes: int64(3) memory usage: 368.0 bytes
 res6.describe()
user_id cate shop_id
count 1.200000e+01 12.000000 12.000000
mean 6.468688e+05 10.666667 3594.000000
std 3.988181e+05 6.665151 373.271775
min 2.421410e+05 7.000000 3388.000000
25% 3.901920e+05 7.000000 3388.000000
50% 4.938730e+05 7.000000 3388.000000
75% 9.824990e+05 10.250000 3586.250000
max 1.558165e+06 23.000000 4278.000000
 res6
user_id cate shop_id
0 390192 20 4178
1 390192 23 4179
2 390192 22 4278
3 1021819 7 3388
4 242141 7 3388
5 283284 7 3388
6 1558165 7 3388
7 533696 7 3388
8 982499 7 3388
9 493873 7 3388
10 493873 7 3388
11 982499 7 3389
 res6['user_id'].value_counts() 
 390192     3 982499     2 493873     2 242141     1 1021819    1 533696     1 1558165    1 283284     1 Name: user_id, dtype: int64
 res6.groupby(['user_id']).size().sort_values(ascending=False) 
 user_id 390192     3 982499     2 493873     2 1558165    1 1021819    1 533696     1 283284     1 242141     1 dtype: int64 
 res6.groupby(['user_id', 'cate']).size().sort_values(ascending=False) 
 user_id  cate 982499   7       2 493873   7       2 1558165  7       1 1021819  7       1 533696   7       1 390192   23      1 22      1 20      1 283284   7       1 242141   7       1 dtype: int64 
 res6_test = res6.groupby(['user_id', 'cate', 'shop_id']).size().sort_values(ascending=False) res6_test
 user_id  cate  shop_id 493873   7     3388       2 1558165  7     3388       1 1021819  7     3388       1 982499   7     3389       1 3388       1 533696   7     3388       1 390192   23    4179       1 22    4278       1 20    4178       1 283284   7     3388       1 242141   7     3388       1 dtype: int64

到此这篇关于python中pandas对多列进行分组统计的实现的文章就介绍到这了,更多相关pandas多列分组统计内容请搜索gaodaima搞代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持gaodaima搞代码网

以上就是python中pandas对多列进行分组统计的实现的详细内容,更多请关注gaodaima搞代码网其它相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:python中pandas对多列进行分组统计的实现
喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址