[英]Groupby count as one column and groupby number of unique values of another column in pandas
[英]Pandas unique count of number of records in a column where mutliple values are present in another column
我正在嘗試計算Customer_Key的唯一數量,其中Broad_Category列具有按Month列中的值分組的值A和B 。 示例數據框如下
Customer_Key | 類別 | 月 |
---|---|---|
CK123 | 一個 | 2 |
CK234 | 一個 | 2 |
CK234 | 乙 | 2 |
CK680 | 一個 | 3 |
CK123 | 乙 | 3 |
CK123 | 一個 | 3 |
CK356 | 乙 | 3 |
CK345 | 一個 | 4 |
預期的結果是
月 | 獨特客戶 |
---|---|
2 | 1 |
3 | 1 |
4 | 0 |
我在這里想不出什么。 任何線索/幫助將不勝感激。 提前致謝。 強調文本
嘗試這樣的事情:
df.groupby(['Customer_Key', 'Month']) \
.sum() \
.query("Category in ('AB','BA')") \
.groupby('Month') \
.count() \
.rename(columns={'Category': 'Unique Customers'})
編輯...
這個解決方案的問題是它不計算月份為 0。我准備了一個修復:
import pandas as pd
import sys
if sys.version_info[0] < 3:
from StringIO import StringIO
else:
from io import StringIO
data = StringIO("""ck123 A 2
ck234 A 2
ck234 B 2
ck680 A 3
ck123 B 3
ck123 A 3
ck356 B 3
ck345 A 4""")
df1 = df.groupby(['Customer_Key', 'Month']) \
.sum() \
.reset_index()
def map_categories(row):
if row['Category'] in ('AB', 'BA'):
return 1
else:
return 0
df1['Unique Customers'] = df1.apply(lambda row: map_categories(row), axis=1)
df1 = df1.groupby('Month')['Unique Customers'].sum().reset_index()
這是實現它的一種方法
首先它按月份和客戶分組,讓我們在一個月內獲得客戶以及類別的數量。 結果進一步按月份分組,我們選擇最大計數。
減少計數為我們提供了屬於這兩個類別的唯一客戶的所需計數
希望能幫助到你
df2=df.groupby(['Month','Customer_Key']).count().reset_index().groupby(['Month'])['Category'].max().reset_index()
df2['Category'] = df2['Category'] -1
df2.rename(columns={'Category': 'Unique Cusomter'}, inplace=True)
df2
Month Unique Cusomter
0 2 1
1 3 1
2 4 0
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.