温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

python中如何使用pandas对多列进行分组统计

发布时间:2021-06-21 11:12:09 来源:亿速云 阅读:520 作者:小新 栏目:开发技术

这篇文章主要介绍了python中如何使用pandas对多列进行分组统计,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。

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

python中如何使用pandas对多列进行分组统计

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

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

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()
<class 'pandas.core.frame.DataFrame'>
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_idcateshop_id
count1.200000e+0112.00000012.000000
mean6.468688e+0510.6666673594.000000
std3.988181e+056.665151373.271775
min2.421410e+057.0000003388.000000
25%3.901920e+057.0000003388.000000
50%4.938730e+057.0000003388.000000
75%9.824990e+0510.2500003586.250000
max1.558165e+0623.0000004278.000000
res6

user_idcateshop_id
0390192204178
1390192234179
2390192224278
3102181973388
424214173388
528328473388
6155816573388
753369673388
898249973388
949387373388
1049387373388
1198249973389
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对多列进行分组统计”这篇文章对大家有帮助,同时也希望大家多多支持亿速云,关注亿速云行业资讯频道,更多相关知识等着你来学习!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI