[英]Pandas Groupby nunique count based on grouping of 2 date lists
與此問題類似,但再增加一個步驟: 根據開始和結束日期滾動 groupby 唯一計數
我有一個帶有唯一 ID、開始日期、結束日期、開始年份和結束年份的數據框。 在這段時間內,ID 可以啟動、停止和重新啟動。
我想在全年中獲得一個 groupby 唯一的 ID 計數。 目前,我可以計算 ID 的開始日期和結束日期的唯一值,但我究竟如何合並包括年份在內?
fun = pd.DataFrame({'ZIP_KEY': ['A', 'B', 'A'],
'start_month': [1, 2, 2],
'end_month': [4, 3, 7],
'start_year': [2016, 2016, 2017],
'end_year': [2016, 2017, 2018]})
fun["month_list"] = fun.apply(lambda x: list(range(x["start_month"], x["end_month"]+1)), axis=1)
fun["year_list"] = fun.apply(lambda x: list(range(x["start_year"], x["end_year"]+1)), axis=1)
fun = fun.explode("month_list")
fun = fun.explode("year_list")
fun.groupby(["year_list", "month_list"])["ZIP_KEY"].nunique()
year_list month_list
2016 1 1
2 2
3 2
4 1
2017 2 2
3 2
4 1
5 1
6 1
7 1
2018 2 1
3 1
4 1
5 1
6 1
7 1
如果 Zip Key 是多年的,我目前的方法沒有考慮全年 --> 從 2018 年 1 月開始,到 2020 年 2 月結束,然后我們得到[1,2]
和[2018,2019,2020]
,而不是全年2018 年和 2019 年。我應該得到[1,2,3,4,5,6,7,8,9,10,11,12]
的[2018, 2019]
和[1,2]
的 2020 年
與我的其他答案類似,但這次我們使用pd.date_range
和'MS'
頻率而不是range
。 首先為所提供的年月組合創建每月第一天的datetime
列會很有幫助。
import pandas as pd
# Create start and end datetime column.
for per in ['start', 'end']:
fun[per] = pd.to_datetime(fun[[f'{per}_year', f'{per}_month']]
.rename(columns={f'{per}_year': 'year', f'{per}_month': 'month'})
.assign(day=1))
df = pd.concat([pd.DataFrame({'date': pd.date_range(st, en, freq='MS'), 'key': k})
for k, st, en in zip(fun['ZIP_KEY'], fun['start'], fun['end'])])
現在分組輸出。 如果你想要單獨的列:
df.groupby([df.date.dt.year.rename('year'), df.date.dt.month.rename('month')]).key.nunique()
year month
2016 1 1 # <━┓
2 2 # <━╋━━┓
3 2 # A ┃
4 2 # <━┛ ┃
5 1 # ┃
6 1 # ┃
7 1 # ┃
8 1 # B
9 1 # ┃
10 1 # ┃
11 1 # ┃
12 1 # ┃
2017 1 1 # ┃
2 2 # <━━━━╋━┓
3 2 # <━━━━┛ ┃
4 1 # ┃
5 1 # ┃
6 1 # ┃
7 1 # ┃
8 1 # ┃
9 1 # ┃
10 1 # A
11 1 # ┃
12 1 # ┃
2018 1 1 # ┃
2 1 # ┃
3 1 # ┃
4 1 # ┃
5 1 # ┃
6 1 # ┃
7 1 # <━━━━━━┛
我有時更喜歡按時期分組:
df.groupby(df.date.dt.to_period('M')).key.nunique()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.