python - 如何更改python代码中pd.DateOffset中的参数?

标签 python datetimeoffset

我有两种不同类型的数据。第一个数据帧以小时为单位,第二个数据帧以分钟为单位。所以,我需要分别提前24小时和30分钟预测这个数据。但我无法使我创建的函数能够使用这两种数据框。

比方说,我想将我的数据集划分为训练数据集和测试数据集。

如果我的数据以小时为单位,我需要使用函数hours

def split_data(df, tend):       
    train=df[:index-pd.DateOffset(hours=1)]
    test=df[index:index+pd.DateOffset(hours=tend-1)]

如果我的数据以分钟为单位,我需要使用函数分钟

def split_data(df, tend):       
    train=df[:index-pd.DateOffset(minutes=1)]
    test=df[index:index+pd.DateOffset(minutes=tend-1)]

我已经尝试忽略时间函数,但未能将数据拆分为分钟和每小时数据

def split_data(df, tend):       
    train=df[:index-pd.DateOffset(1)]
    test=df[index:index+pd.DateOffset(tend-1)]

我期望该函数可以在两种数据帧上工作,我也尝试分配该函数,但失败了。

最佳答案

我认为您需要使用关键字参数来传递多个值,如下所示:

ts = pd.Timestamp('2017-01-01 09:10:11')
ts
Timestamp('2017-01-01 09:10:11')

ts + pd.DateOffset(months=3)
Timestamp('2017-04-01 09:10:11')

ts + pd.DateOffset(days=3)
Timestamp('2017-01-04 09:10:11')

custom_args = {"days":1, "hours":3} # pass variable number of arguments
ts + pd.DateOffset(**custom_args)
Timestamp('2017-01-02 12:10:11')

custom_args = {"days":1, "hours":0}
ts + pd.DateOffset(**custom_args)
Timestamp('2017-01-02 09:10:11')

custom_args = {"days":1, "hours":0, "minutes":0}
ts + pd.DateOffset(**custom_args)
Timestamp('2017-01-02 09:10:11')

对于您的情况,您可以尝试以下方式:

def split_data(df, tend, custom_args, unit="hours"): # or unit can be minutes  
    custom_args[unit] = 1
    train=df[:index-pd.DateOffset(**custom_args)]
    custom_args[unit] = tend - 1
    test=df[index:index+pd.DateOffset(**custom_args)]

custom_args = {"hours":0, "minutes":0, "minutes":0} # you can specify more arguments based on your requirements.
split_data(df, tend, custom_args, unit="hours")

要查看您可以传递的所有参数,请查看此链接 https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.tseries.offsets.DateOffset.html

关于python - 如何更改python代码中pd.DateOffset中的参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56230365/

相关文章:

oracle - "TIMESTAMP WITH TIME ZONE"<--> DateTImeOffset 映射不会在 INSERT 命令上传递区域部分( Entity Framework + Oracle)

c# - 为什么 DateTime.TryParseExact() 会为这些输入字符串返回不同的时区?

c# - 将日期时间转换为特定时区但采用特定格式 c#

python - pandas 日期时间格式转换

python - 无法对对象 : pymongo. 光标进行编码。光标对象位于

python - 通过网络传输 Protocol Buffer 的规范方式?

python - Pandas:累积函数应用

python - 安装Python模块六

sql-server-2008 - 将 DATETIMEOFFSET 列过滤为本地日期范围

python - 上次文件修改时间返回自 DST 更改以来一年的偏移量