pandas pivot_table或者groupby實現sql 中的count distinct 功能

pandas pivot_table或者groupby實現sql 中的count distinct 功能

import pandas as pd
import numpy as np
data = pd.read_csv('活躍買家分析初稿.csv')
data.head()
recycler_key date 周 date 年 date 月 記錄數
0 1694 周 1 2018 一月 6
1 1693 周 1 2018 一月 14
2 1686 周 1 2018 一月 20
3 1677 周 1 2018 一月 62
4 1676 周 1 2018 一月 25
  • 咱們發現表格的表頭有空格,且看起來不舒服,嘗試使用上篇文章的更名功能,將表頭修改成合理的格式
data.columns=['merchant','week','year','month','records']
data.head()
merchant week year month records
0 1694 周 1 2018 一月 6
1 1693 周 1 2018 一月 14
2 1686 周 1 2018 一月 20
3 1677 周 1 2018 一月 62
4 1676 周 1 2018 一月 25
  • 咱們的目標就是統計每一個天然月內對應每一個客戶提交的周次數
  • 一樣的原理,咱們也能夠統計天然月內客戶數

方法一: 多重groupby,較爲麻煩

  • 首先利用groupby求出每月中商家提交訂單數
data1 =data.groupby(['month','merchant']).size()
data1.head()
month  merchant
一月     1           2
       240         1
       241         1
       256         9
       277         2
dtype: int64
  • 重建索引
data1.reset_index().head()
month merchant 0
0 一月 1 2
1 一月 240 1
2 一月 241 1
3 一月 256 9
4 一月 277 2
  • 將重建索引的生成的dataFrame再次groupby
data1.reset_index().groupby('month')['merchant'].size().reindex(['一月','二月','三月','四月','五月','六月','七月','八月','九月','十月','十一月','十二月']).reset_index()
month merchant
0 一月 615
1 二月 622
2 三月 359
3 四月 175
4 五月 209
5 六月 258
6 七月 320
7 八月 366
8 九月 417
9 十月 428
10 十一月 522
11 十二月 617

方法2 pivot_table使用aggfunc 實現nunique方法

data2=data.pivot_table(index='month',values='merchant',aggfunc=lambda x:len(x.unique()))
data2.reindex(['一月','二月','三月','四月','五月','六月','七月','八月','九月','十月','十一月','十二月']).reset_index()
month merchant
0 一月 615
1 二月 622
2 三月 359
3 四月 175
4 五月 209
5 六月 258
6 七月 320
7 八月 366
8 九月 417
9 十月 428
10 十一月 522
11 十二月 617

方法3,直接採用Series的nunique方法

data3 = data.pivot_table(index='month',values='merchant',aggfunc=pd.Series.nunique)
data3.reindex(['一月','二月','三月','四月','五月','六月','七月','八月','九月','十月','十一月','十二月']).reset_index()
month merchant
0 一月 615
1 二月 622
2 三月 359
3 四月 175
4 五月 209
5 六月 258
6 七月 320
7 八月 366
8 九月 417
9 十月 428
10 十一月 522
11 十二月 617

方法4 使用單個的groupby,聚合使用nunique方法

data4 = data.groupby(['month']).agg({'merchant': pd.Series.nunique})
data4.reindex(['一月','二月','三月','四月','五月','六月','七月','八月','九月','十月','十一月','十二月']).reset_index()
month merchant
0 一月 615
1 二月 622
2 三月 359
3 四月 175
4 五月 209
5 六月 258
6 七月 320
7 八月 366
8 九月 417
9 十月 428
10 十一月 522
11 十二月 617

能夠參考

相關文章
相關標籤/搜索