我試圖在Python中建立一個函式,如果用戶提供一個偏移頻率,如1D 10M 1Y,那么我可以使用該偏移量提供日期。
例如,如果用戶輸入1M以及一個日期2021-08-25
pd.Timestamp('2021-08-25'/span>) - pd.tseries.frequencies.to_offset('1M'/span>)
上面的代碼輸出Timestamp('2021-07-31 00:00:00'),這不是用戶提供的日期之前的一個月。預期輸出 Timestamp('2021-07-25 00:00:00')/code>
我怎樣才能做到這一點?
uj5u.com熱心網友回復:你需要使用pd.DateOffset:
>>> pd.Timestamp("2020-08-25"/span>) - pd.DateOffset(month=1)
Timestamp('2020-07-25 00:00:00')
frequencies.to_offset()回傳一個<MonthEnd>物件,因此你會得到07-31:
>>> pd.tseries.frequencies.to_offset("1M"/span>)
<月末>。
uj5u.com熱心網友回復:
由于年和月沒有固定的頻率,你可以使用pd.offsets.DateOffset方法來處理年和月的日歷添加,類似于relativedelta的實作。
因為你需要同時指定引數names和values才能作業,你可以改變你的函式來傳遞一個dict與引數,而不僅僅是偏移頻率。
import pandas as pd
def offset_date(timestamp, offset)。
""
offset: dict of {'offset frequency': periods}.
""
return timestamp pd.offsets.DateOffset(**offset)
Timestamp = pd.Timestamp('2021-08-25')
offset_date(timestamp, {'month': 1})
#Timestamp('2021-09-25 00:00:00')
offset_date(timestamp, {'days': 10})
#Timestamp('2021-09-04 00:00:00')
offset_date(timestamp, {'year': -3})
#Timestamp('2018-08-25 00:00:00')
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/311902.html
標籤:
