直接使用Pandas日期偏移和偏移别名

我确定我不是在搜索正确的短语来回答这个问题,但是在Pandas中,可以使用DateTimeset来获取任何DateTime对象并从中添加或减去:

pd.datetime.now() + pd.DateOffset(months=2)

pd.datetime.now() + pd.DateOffset(weeks=4)

pd.datetime.now() + pd.DateOffset(days=2)

但是在不同的上下文中,还使用了偏移别名: https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#offset-aliases

我的问题是是否可以使用DateOffset并传递Offset Alias来确定Offset基础?

例如,pd.datetime.now() + pd.DateOffset(n=some_int,freq='W')个星期some_int个星期?

如果不可能的话,我应该在哪里挖掘一些有用的东西?

(原因是因为有一个函数我正在使用偏移别名,并且我不想创建很长的if ... else语句来将freq字符串转换为{{1}的不同实例}我宁愿用freq字符串在一行代码中指定DateOffset,而且仍然动态地处理不同的时间频率。)

编辑:添加一个满足我需要的自定义函数,但是最好在to_timedelta或DateOffset中有一个解决方案,以便该解决方案在上游且效率更高。例如,我很想利用我正在使用的所有pd.DateOffset(weeks=n | years=n | months=n | etc.)参数的商业版本,以便freq可以更自然地获取原始信息。 >

n
iCMS 回答:直接使用Pandas日期偏移和偏移别名

我认为to_timedelta function在做什么。

time = pd.datetime.now() + pd.to_timedelta(5,unit='W')

更新
to_timedelta函数不再支持月份,季度和年份。时间偏移对象有两种:

  • 尊重日历时间的DateOffset:
  • TimeOffset,它是绝对时间(与夏令时天数有关)。

使用documentation about it获得更多详细信息。 to_timedelta函数无法知道您要使用哪个。

,

也许此功能会有所帮助?

def offset(freq:str,n:int = 0):
    """
    Pandas DateOffset wrapper
    import pandas as pd
    """
    # =============================================================================
    # offsets_df = pd.read_html('https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html')[2]
    # offsets_df.drop(columns = ['Description'],inplace = True)
    # offsets_df.replace('None',np.NaN,inplace = True)
    # offsets_df.dropna(subset = ['Frequency String'],inplace = True)
    # offsets_df['Frequency String'] = offsets_df['Frequency String'].str.replace("\'",'')
    # for x in ['Date Offset','Frequency String']:
    #    offsets_df[x] =  offsets_df[x].str.split(' or ')
    # offsets_df['Date Offset'] = offsets_df['Date Offset'].map(lambda x: x[0])
    # offsets_df = explode_rows(offsets_df,'Frequency String',fill_value = '')
    # offsets_df.drop_duplicates(subset = ['Frequency String'],inplace = True)
    # offsets_d = dict(zip(offsets_df['Frequency String'],offsets_df['Date Offset']))
    # =============================================================================
    offsets_d = {'B': 'BDay','C': 'CDay','W': 'Week','WOM': 'WeekOfMonth','LWOM': 'LastWeekOfMonth','M': 'MonthEnd','MS': 'MonthBegin','BM': 'BMonthEnd','BMS': 'BMonthBegin','CBM': 'CBMonthEnd','CBMS': 'CBMonthBegin','SM': 'SemiMonthEnd','SMS': 'SemiMonthBegin','Q': 'QuarterEnd','QS': 'QuarterBegin','BQ': 'BQuarterEnd','BQS': 'BQuarterBegin','REQ': 'FY5253Quarter','A': 'YearEnd','AS': 'YearBegin','BYS': 'YearBegin','BA': 'BYearEnd','BAS': 'BYearBegin','RE': 'FY5253','BH': 'BusinessHour','CBH': 'CustomBusinessHour','D': 'Day','H': 'Hour','T': 'Minute','min': 'Minute','S': 'Second','L': 'Milli','ms': 'Milli','U': 'Micro','us': 'Micro','N': 'Nano'}
    return eval(f'pd.offsets.{offsets_d[freq]}({n})')
本文链接:https://www.f2er.com/1514207.html

大家都在问