网络编程
位置:首页>> 网络编程>> Python编程>> python中pandas对多列进行分组统计的实现

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

作者:光于前裕于后  发布时间:2022-06-25 03:50:03 

标签: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

来源:https://drguo.blog.csdn.net/article/details/89670842

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com