看到上述错误的几个回复,但culdn没有弄清楚我的代码中的错误。我正在关注教程:https://pythonprogramming.net/unix-time-matplotlib-tutorial/?completed=/basic-customization-matplotlib-tutorial/并遇到上述错误。
我可以用这三行代码重现这个问题:
import numpy as np
L = ['2017-07-26,153.3500,153.9300,153.0600,153.5000,153.5000,12778195.00',
'2017-07-25,151.8000,153.8400,151.8000,152.7400,152.7400,18714400.00',
'2017-07-24,150.5800,152.4400,149.9000,152.0900,152.0900,21304700.00']
date, closep, highp, lowp, openp, adj_closep, volume = np.loadtxt(L,
delimiter=',',
unpack=True)
错误跟踪是:
ValueError Traceback (most recent call last)
<ipython-input-2-bae25d428491> in <module>()
5 date, closep, highp, lowp, openp, adj_closep, volume = np.loadtxt(L,
6 delimiter=',',
----> 7 unpack=True)
/usr/local/lib/python3.5/dist-packages/numpy/lib/npyio.py in loadtxt(fname, dtype, comments, delimiter, converters, skiprows, usecols, unpack, ndmin)
1022
1023 # Convert each value according to its column and store
-> 1024 items = [conv(val) for (conv, val) in zip(converters, vals)]
1025 # Then pack it according to the dtype's nesting
1026 items = pack_items(items, packing)
/usr/local/lib/python3.5/dist-packages/numpy/lib/npyio.py in <listcomp>(.0)
1022
1023 # Convert each value according to its column and store
-> 1024 items = [conv(val) for (conv, val) in zip(converters, vals)]
1025 # Then pack it according to the dtype's nesting
1026 items = pack_items(items, packing)
/usr/local/lib/python3.5/dist-packages/numpy/lib/npyio.py in floatconv(x)
723 if b'0x' in x:
724 return float.fromhex(asstr(x))
--> 725 return float(x)
726
727 typ = dtype.type
ValueError: could not convert string to float: b'2017-07-26'
请让我知道如何解决它。
答案 0 :(得分:2)
/
在无法将字符串转换为float
genfromtxt
nan
跳过第一栏
In [353]: np.genfromtxt(L, delimiter=',')
Out[353]:
array([[ nan, 1.5335000e+02, 1.5393000e+02, 1.5306000e+02,
1.5350000e+02, 1.5350000e+02, 1.2778195e+07],
[ nan, 1.5180000e+02, 1.5384000e+02, 1.5180000e+02,
1.5274000e+02, 1.5274000e+02, 1.8714400e+07],
[ nan, 1.5058000e+02, 1.5244000e+02, 1.4990000e+02,
1.5209000e+02, 1.5209000e+02, 2.1304700e+07]])
带有日期和浮点字段的结构化数组:
In [357]: np.loadtxt(L, delimiter=',',usecols=np.arange(1,7))
Out[357]:
array([[1.5335000e+02, 1.5393000e+02, 1.5306000e+02, 1.5350000e+02,
1.5350000e+02, 1.2778195e+07],
[1.5180000e+02, 1.5384000e+02, 1.5180000e+02, 1.5274000e+02,
1.5274000e+02, 1.8714400e+07],
[1.5058000e+02, 1.5244000e+02, 1.4990000e+02, 1.5209000e+02,
1.5209000e+02, 2.1304700e+07]])
自己约会:
In [360]: np.loadtxt(L, delimiter=',',dtype='datetime64[D],f,f,f,f,f,f')
Out[360]:
array([('2017-07-26', 153.35, 153.93, 153.06, 153.5 , 153.5 , 12778195.),
('2017-07-25', 151.8 , 153.84, 151.8 , 152.74, 152.74, 18714400.),
('2017-07-24', 150.58, 152.44, 149.9 , 152.09, 152.09, 21304700.)],
dtype=[('f0', '<M8[D]'), ('f1', '<f4'), ('f2', '<f4'), ('f3', '<f4'), ('f4', '<f4'), ('f5', '<f4'), ('f6', '<f4')])