【问题标题】:Numpy: TypeError: float() argument must be a string or a number, not 'Timestamp'Numpy:TypeError:float()参数必须是字符串或数字,而不是“时间戳”
【发布时间】:2020-07-13 19:56:38
【问题描述】:

我知道存在类似的问题,但仍未得到解答,请在此处提供帮助,我是数据处理的新手,出现了 因此,在这样做的同时,我将observation_dates 作为列表bcoz matplotlib can't handle generators 是我遇到的一个错误,解决了这个问题

我的代码:

import matplotlib.pyplot as plt
import numpy as np
plt.figure()
observation_dates = np.arange('2017-01-01', '2017-01-09', dtype='datetime64[D]')
observation_dates = list(map(pd.to_datetime, observation_dates)) 
plt.plot(observation_dates, linear_data, '-o',  observation_dates, exponential_data, '-o')

我在 Jupyter Notebook 上遇到的错误:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-37-2e5ff380987f> in <module>
      2 observation_dates = np.arange('2017-01-01', '2017-01-09', dtype='datetime64[D]')
      3 observation_dates = list(map(pd.to_datetime, observation_dates)) # convert the map to a list to get rid of the error
----> 4 plt.plot(observation_dates, linear_data, '-o',  observation_dates, exponential_data, '-o')

~\anaconda3\lib\site-packages\matplotlib\pyplot.py in plot(scalex, scaley, data, *args, **kwargs)
   2794     return gca().plot(
   2795         *args, scalex=scalex, scaley=scaley, **({"data": data} if data
-> 2796         is not None else {}), **kwargs)
   2797 
   2798 

~\anaconda3\lib\site-packages\matplotlib\axes\_axes.py in plot(self, scalex, scaley, data, *args, **kwargs)
   1665         lines = [*self._get_lines(*args, data=data, **kwargs)]
   1666         for line in lines:
-> 1667             self.add_line(line)
   1668         self.autoscale_view(scalex=scalex, scaley=scaley)
   1669         return lines

~\anaconda3\lib\site-packages\matplotlib\axes\_base.py in add_line(self, line)
   1900             line.set_clip_path(self.patch)
   1901 
-> 1902         self._update_line_limits(line)
   1903         if not line.get_label():
   1904             line.set_label('_line%d' % len(self.lines))

~\anaconda3\lib\site-packages\matplotlib\axes\_base.py in _update_line_limits(self, line)
   1922         Figures out the data limit of the given line, updating self.dataLim.
   1923         """
-> 1924         path = line.get_path()
   1925         if path.vertices.size == 0:
   1926             return

~\anaconda3\lib\site-packages\matplotlib\lines.py in get_path(self)
   1025         """
   1026         if self._invalidy or self._invalidx:
-> 1027             self.recache()
   1028         return self._path
   1029 

~\anaconda3\lib\site-packages\matplotlib\lines.py in recache(self, always)
    668         if always or self._invalidx:
    669             xconv = self.convert_xunits(self._xorig)
--> 670             x = _to_unmasked_float_array(xconv).ravel()
    671         else:
    672             x = self._x

~\anaconda3\lib\site-packages\matplotlib\cbook\__init__.py in _to_unmasked_float_array(x)
   1388         return np.ma.asarray(x, float).filled(np.nan)
   1389     else:
-> 1390         return np.asarray(x, float)
   1391 
   1392 

~\anaconda3\lib\site-packages\numpy\core\_asarray.py in asarray(a, dtype, order)
     83 
     84     """
---> 85     return array(a, dtype, copy=False, order=order)
     86 
     87 

TypeError: float() argument must be a string or a number, not 'Timestamp'

【问题讨论】:

  • plt.plot() 中的哪些参数您将参数传递给?您只能通过一个 x 范围和一个 y 范围。看起来您正在尝试传递多个范围。制作两个单独的图。

标签: python numpy jupyter


【解决方案1】:

matplotlib.pyplot 支持使用Datetime 对象进行绘图。您使用通过将pd.to_datetime() 映射到observation_dates 生成的Timestamp 对象。您需要将numpydatetime64[D] 转换为datetime.datetime。由于您的日期已经是 ISO 格式,一种简单的方法是对转换为字符串的日期使用列表推导并调用 fromisoformat() 方法。

import datetime
import matplotlib.pyplot as plt
import numpy as np
plt.figure()
observation_dates = np.arange('2017-01-01', '2017-01-09', dtype='datetime64[D]')
observation_dates = [datetime.datetime.fromisoformat(str(date)) for date in observation_dates]
plt.plot(observation_dates, linear_data, '-o',  observation_dates, exponential_data, '-o')

您也可以使用strptime() 方法作为fromisoformat() 的替代方法:

[datetime.datetime.strptime(str(date), '%Y-%m-%d') for date in observation_dates]

【讨论】:

    猜你喜欢
    • 2019-07-07
    • 2019-05-22
    • 2020-09-18
    • 2019-06-27
    • 1970-01-01
    • 2017-08-29
    • 1970-01-01
    • 2019-03-02
    相关资源
    最近更新 更多