【问题标题】:"AttributeError: 'matrix' object has no attribute 'strftime'" error in numpy pythonnumpy python中的“AttributeError:'matrix'对象没有属性'strftime'”错误
【发布时间】:2015-10-10 14:28:36
【问题描述】:

我有一个 (72000, 1) 维度的矩阵。该矩阵涉及时间戳。

我想使用“strftime”如下; strftime("%d/%m/%y"),为了得到这样的输出:'11/03/02'

我有这样一个矩阵:

M = np.matrix([timestamps])

我使用“strftime”将所有涉及时间戳的矩阵转换为涉及字符串类型日期的矩阵。出于这个原因,我使用了“strftime”作为以下内容:

M = M.strftime("%d/%m/%y")

当我运行代码时,我得到这个错误:

AttributeError: 'matrix' object has no attribute 'strftime'

使用此功能的正确方法是什么?如何将时间戳矩阵转换为日期字符串矩阵?

【问题讨论】:

  • 那么M的形状是(72000,1) ?
  • 我建议阅读np.datetime64 dtype。
  • 感谢您的建议。

标签: python numpy matrix strftime


【解决方案1】:

正如错误消息显示的那样,您不能执行 matrix.strftime 之类的操作。您可以做的一件事是使用 numpy.apply_along_axis 。示例 -

np.apply_along_axis((lambda x:[x[0].strftime("%d/%m/%y")]),1,M)

演示 -

In [58]: M = np.matrix([[datetime.datetime.now()]*5]).T

In [59]: M.shape
Out[59]: (5, 1)

In [60]: np.apply_along_axis((lambda x:[x[0].strftime("%d/%m/%y")]),1,M)
Out[60]:
array([['10/10/15'],
       ['10/10/15'],
       ['10/10/15'],
       ['10/10/15'],
       ['10/10/15']],
      dtype='<U8')

对于您遇到的新错误 -

"AttributeError: 'numpy.float64' 对象没有属性 'strftime'"

这意味着对象不是datetime对象,所以如果它们是时间戳,你可以先将它们转换为日期时间。示例 -

np.apply_along_axis((lambda x:[datetime.datetime.fromtimestamp(x[0]).strftime("%d/%m/%y")]),1,M)

【讨论】:

  • 感谢您的回答 Anand,但我必须转换一个仅涉及时间戳的矩阵。我该如何管理?
  • 不,它没有。我收到此错误:“AttributeError: 'numpy.float64' 对象没有属性 'strftime'”
  • 先尝试datetime.datetime.fromtimestamp() 转换为日期时间,答案中给出的示例。
猜你喜欢
  • 2021-10-12
  • 2013-11-22
  • 2023-03-22
  • 2018-10-02
  • 2021-01-19
  • 2014-04-03
  • 2023-03-05
  • 2011-06-19
  • 2020-09-28
相关资源
最近更新 更多