float()的文字无效:01/06/2017 22:00

时间:2017-06-13 11:24:52

标签: python csv date pandas

数据来自csv文件,我用pandas读它。我用pyplot绘图,它应该就像:x作为时间,y作为风速。我认为问题是由选择或索引引起的。我只想要第22-25行的数据然后绘制它。以下是数据和代码:

      time              Unnamed: 2
22    01/06/2017 13:00  23 
23    01/06/2017 16:00  22
24    01/06/2017 19:00  15
25    01/06/2017 22:00  10


import pandas as pd
import matplotlib.pyplot as plt
a = pd.read_csv('J:/internship/forecast/6.1/forecast_report_Bahrain.csv')
m10wind = a['Unnamed: 2'][22:26]
time= a['time'][22:26]
fig, ax = plt.subplots()
fig,ax.set_xlabel("Time(+3UTC)")
fig,ax.set_ylabel("10m wind speed (knots)")
ax.plot(time, m10wind, 'r', label='GFS Forecast')
leg = ax.legend(loc=2, bbox_to_anchor=(1.05, 1.0))
plt.savefig('1st June wind of Bahrain.png', bbox_inches='tight')
plt.show()

完整的错误消息:

Traceback (most recent call last):

  File "<ipython-input-37-9ab81b2b3775>", line 1, in <module>
    runfile('C:/Users/xiaoshen.sun/.spyder/temp.py', wdir='C:/Users/xiaoshen.sun/.spyder')

  File "C:\tools\Python2.7\lib\site-packages\spyder\utils\site\sitecustomize.py", line 866, in runfile
    execfile(filename, namespace)

  File "C:\tools\Python2.7\lib\site-packages\spyder\utils\site\sitecustomize.py", line 87, in execfile
    exec(compile(scripttext, filename, 'exec'), glob, loc)

  File "C:/Users/xiaoshen.sun/.spyder/temp.py", line 18, in <module>
    ax.plot(time, m10wind, 'r', label='GFS Forecast')

  File "C:\tools\Python2.7\lib\site-packages\matplotlib\__init__.py", line 1891, in inner
    return func(ax, *args, **kwargs)

  File "C:\tools\Python2.7\lib\site-packages\matplotlib\axes\_axes.py", line 1407, in plot
    self.add_line(line)

  File "C:\tools\Python2.7\lib\site-packages\matplotlib\axes\_base.py", line 1787, in add_line
    self._update_line_limits(line)

  File "C:\tools\Python2.7\lib\site-packages\matplotlib\axes\_base.py", line 1809, in _update_line_limits
    path = line.get_path()

  File "C:\tools\Python2.7\lib\site-packages\matplotlib\lines.py", line 989, in get_path
    self.recache()

  File "C:\tools\Python2.7\lib\site-packages\matplotlib\lines.py", line 676, in recache
    x = np.asarray(xconv, np.float_)

  File "C:\tools\Python2.7\lib\site-packages\numpy\core\numeric.py", line 482, in asarray
    return array(a, dtype, copy=False, order=order)

ValueError: invalid literal for float(): 01/06/2017 22:00

1 个答案:

答案 0 :(得分:1)

您的问题(可能)与datetime列未被格式化有关。我能够使用pd.to_datetime()转换列并绘制此数据而没有任何问题。你的绘图也是不正确的,可能会抛出一个错误 - fig, ax意味着解包一个元组。 ax包含plot方法(见下文)。

df
                  time  Unnamed: 2
22 2017-01-06 13:00:00          23
23 2017-01-06 16:00:00          22
24 2017-01-06 19:00:00          15
25 2017-01-06 22:00:00          10

转换:

df.time = pd.to_datetime(df.time)

简介:

fig, ax = plt.subplots()
ax.plot(df.time, df['Unnamed: 2'])
plt.tight_layout()
plt.show()

enter image description here