我正在嘗試在熊貓中創建一個財政季度列。如果財政年度結束是 3 月,我可以使用以下代碼執行此操作:
df['fiscalquarter'] = df['Date'].dt.to_period('Q-MAR')
但是,我想使用資料框中具有月份縮寫的列而不是“MAR”。我的列值是 JAN、FEB、MAR 等。如何告訴 pandas 查看該列(財政月)中的值來創建季度?
列印輸出(df.head()):
ID fiscalmonth Date DateSubYear fiscalmonthabr
5021 1 2 2001-03-29 2001 FEB
5780 2 2 2001-04-03 2001 FEB
7024 3 2 2001-05-02 2001 FEB
7307 4 2 2001-05-11 2001 FEB
8076 4 2 2001-06-14 2001 FEB
我想看看:
ID fiscalquater
5021 1 2002Q1
5780 2 2002Q1
7024 3 2002Q1
7307 4 2002Q1
8076 4 2002Q2
uj5u.com熱心網友回復:
您可以使用:
fiscal_quarter = lambda x: x['Date'].to_period(x['fiscalmonthabr'])
df['fiscalquater'] = df.assign(fiscalmonthabr='Q-' df['fiscalmonthabr'],
Date=pd.to_datetime(df['Date'])) \
.apply(fiscal_quarter, axis=1)
print(df)
# Output
ID fiscalmonth Date DateSubYear fiscalmonthabr fiscalquater
5021 1 2 2001-03-29 2001 FEB 2002Q1
5780 2 2 2001-04-03 2001 FEB 2002Q1
7024 3 2 2001-05-02 2001 FEB 2002Q1
7307 4 2 2001-05-11 2001 FEB 2002Q1
8076 4 2 2001-06-14 2001 FEB 2002Q2
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/447969.html
