首页 > 解决方案 > 列表到 numpy 数组,不一致的字符串到浮点转换错误

问题描述

我很难理解以下异常,尽管我确信它非常简单。

我有一个 list raw_ticker,具有以下值:

raw_ticker = ['t1INCH:USD', 3.5881, 17907.680602819994, 3.5945, 10610.799208380002, -0.0172, -0.0048, 3.5982, 300068.50303883, 3.9639, 2.7685]

我想将其转换为 numpy array ticker,并指定数据类型:

ticker = np.array(raw_ticker, 
        dtype=[
        ('symbol', str), 
        ('bid', float), 
        ('bid_size', float), 
        ('ask', float), 
        ('ask_size', float), 
        ('day_chg', float), 
        ('day_chg_p', float), 
        ('last', float), 
        ('vol', float), 
        ('high', float), 
        ('low', float)])

我收到以下错误:

无法将字符串转换为浮点数:'t1INCH:USD'

我没有得到,因为我明确指定该字段是字符串,而不是浮点数。

标签: pythonnumpydtype

解决方案


以元组或元组列表的形式提供数据:

In [363]: raw_ticker = ['t1INCH:USD', 3.5881, 17907.680602819994, 3.5945, 10610.799208380002, -
     ...: 0.0172, -0.0048, 3.5982, 300068.50303883, 3.9639, 2.7685]
In [364]: ticker = np.array(tuple(raw_ticker),
     ...:         dtype=[
     ...:         ('symbol', str),
     ...:         ('bid', float),
     ...:         ('bid_size', float),
     ...:         ('ask', float),
     ...:         ('ask_size', float),
     ...:         ('day_chg', float),
     ...:         ('day_chg_p', float),
     ...:         ('last', float),
     ...:         ('vol', float),
     ...:         ('high', float),
     ...:         ('low', float)])
In [365]: ticker
Out[365]: 
array(('', 3.5881, 17907.68060282, 3.5945, 10610.79920838, -0.0172, -0.0048, 3.5982, 300068.50303883, 3.9639, 2.7685),
      dtype=[('symbol', '<U'), ('bid', '<f8'), ('bid_size', '<f8'), ('ask', '<f8'), ('ask_size', '<f8'), ('day_chg', '<f8'), ('day_chg_p', '<f8'), ('last', '<f8'), ('vol', '<f8'), ('high', '<f8'), ('low', '<f8')])

'symbol' dtype 需要一个字符串宽度,例如'U20'。


推荐阅读