np.loadtxt с сообщением ValueError: не удалось преобразовать строку в число с плавающей точкой: b'2017-07-26 ' - PullRequest
0 голосов
/ 25 мая 2018

Увидел пару ответов с вышеупомянутой ошибкой, но не нашел ошибку в моем коде.Я следую инструкциям по адресу: 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'

Пожалуйста, дайте мне знать, как это исправить.

1 Ответ

0 голосов
/ 25 мая 2018

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

даты сами по себе:

In [363]: np.loadtxt(L, delimiter=',',dtype='datetime64[D]',usecols=0)
Out[363]: array(['2017-07-26', '2017-07-25', '2017-07-24'], dtype='datetime64[D]')
...