我有一個資料集 df,我想在其中按 4 個季度分組并在 python 中聚合
資料
id type date count
aa hi Q1 2022 4
aa hi Q2 2022 6
aa hi Q3 2022 7
aa hi Q4 2022 5
aa ok Q1 2022 1
aa ok Q2 2022 1
aa ok Q3 2022 1
aa ok Q4 2022 1
bb hey Q1 2023 5
bb hey Q2 2023 7
bb hey Q3 2023 9
bb hey Q4 2023 6
想要的
id type date count
aa hi 2022 22
aa ok 2022 4
bb hey 2023 27
正在做
df.groupby(['id','date', 'type']).sum()
但是,我試圖將日期創建為年份并洗掉季度。任何建議表示贊賞
uj5u.com熱心網友回復:
幾種方法 - 請注意使用str方法意味著您series將是一個字串,如果需要,將其轉換為 int。
使用 str.split
df.assign(
date=df['date'].str.split(' ',expand=True)[1]
).groupby(['id','type','date']).sum()
count
id type date
aa hi 2022 22
ok 2022 4
bb hey 2023 27
使用str.extract如果您多年來始終顯示為YYYY
df.assign(
date=df['date'].str.extract('(\d{4})')
).groupby(['id','type','date']).sum()
count
id type date
aa hi 2022 22
ok 2022 4
bb hey 2023 27
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/362002.html
