【问题标题】:TypeError: int() argument must be a string, a bytes-like object or a number, not 'slice'TypeError: int() 参数必须是字符串、类似字节的对象或数字,而不是“切片”
【发布时间】:2017-07-18 13:19:36
【问题描述】:

我使用fbprophet 数据集进行时间序列分析。该数据集有两列,分别为datey

  date                 y
January 01, 1992      146376
February 01, 1992     147079 
March 01, 1992        159336   
April 01, 1992        163669
May 01, 1992          170068       


  date        y
01/01/92    146376
01/02/92    147079
01/03/92    159336
01/04/92    163669
01/05/92    170068

我首先使用pd.to_datetime将日期更改为日期时间格式,然后拟合模型model = Prophet().fit(df)。但是,结果一直显示TypeError: int() argument must be a string, a bytes-like object or a number, not 'slice'。有没有办法解决这个问题?

这是我的代码,

df.date = pd.to_datetime(df.date)
df['date'] = df['date'].dt.strftime('%Y-%m-%d')
model = Prophet()
model.fit(df)

当我运行model.fit(df)时,上面提到的TypeError就会出现。

【问题讨论】:

    标签: python pandas numpy time-series


    【解决方案1】:

    大多数回归和分类器方法只接受数字或字符串 dtypes,因此此错误消息抱怨您的 datetime 列。

    假设我们有以下 DataFrame:

    In [63]: df
    Out[63]:
            date       y
    0 1992-01-01  146376
    1 1992-01-02  147079
    2 1992-01-03  159336
    3 1992-01-04  163669
    4 1992-01-05  170068
    

    我们可以创建一个数字列 - UNIX 时间戳(自 1970-01-01 00:00:00 UTC 以来的秒数):

    In [64]: df['unix_ts'] = df.date.astype(np.int64) // 10**9
    
    In [65]: df
    Out[65]:
            date       y    unix_ts
    0 1992-01-01  146376  694224000
    1 1992-01-02  147079  694310400
    2 1992-01-03  159336  694396800
    3 1992-01-04  163669  694483200
    4 1992-01-05  170068  694569600
    

    这就是我们如何将其转换回datetime dtype:

    In [66]: pd.to_datetime(df.unix_ts, unit='s')
    Out[66]:
    0   1992-01-01
    1   1992-01-02
    2   1992-01-03
    3   1992-01-04
    4   1992-01-05
    Name: unix_ts, dtype: datetime64[ns]
    

    【讨论】:

    • 感谢您的回答。但是在使用df['unix_ts'] = df.date.astype(np.int64) // 10**9; df['date'] = pd.to_datetime(df.unix_ts, unit='s'); df = df.drop(labels = ['unix_ts'], axis = 1) 后我仍然得到相同的 TypeError
    【解决方案2】:

    我在使用 Prophet 时遇到了类似的问题。就我而言,问题是“ds”列中的重复日期(即日期)

    我加了

    df=df.drop_duplicates(['date'], keep='last')
    

    (显然,这在功能上没有意义,但它可能会隔离您的问题)

    【讨论】:

    • 是的。我使用resample() 按日期将重复的日期收集在一起。非常感谢!
    猜你喜欢
    • 2023-03-29
    • 1970-01-01
    • 1970-01-01
    • 2019-08-15
    • 2021-01-14
    • 2018-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多