“AttributeError: 'matrix' object has no attribute 'strftime'” error in numpy python

空扰寡人 提交于 2019-12-12 03:24:51

问题


I have a matrix with (72000, 1) dimension. This matrix involves timestamps.

I want to use "strftime" as the following; strftime("%d/%m/%y"), in order to get the output something like this: '11/03/02'.

I have such a matrix:

M = np.matrix([timestamps])

And I have used "strftime" in order to convert all the matrix involving timestamps to a matrix involving dates in string types. For this reason, I have used "strftime" as the follwing:

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

When I run the code, I get this error:

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

What is the right way of using this function? How can I convert the timestamp matrix to date string matrix?


回答1:


As the error message shows you, you cannot do something like matrix.strftime . One thing you can do would be to use numpy.apply_along_axis . Example -

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

Demo -

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')

For the new error you are getting -

"AttributeError: 'numpy.float64' object has no attribute 'strftime'"

This means that the objects are not datetime objects, so if they are timestamps , you can converting them to datetime first. Example -

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


来源:https://stackoverflow.com/questions/33055070/attributeerror-matrix-object-has-no-attribute-strftime-error-in-numpy-pyt

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!