【问题标题】:list to numpy array, inconsistent string to float conversion error [duplicate]列表到numpy数组,不一致的字符串到浮点转换错误[重复]
【发布时间】:2021-08-09 22:56:31
【问题描述】:

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

我有一个列表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数组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'

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

【问题讨论】:

  • numpy 数组只存储具有相同数据类型的值。你确定这就是你想要创建的吗?
  • @norie,他指定了一个dtype,一个复合的。 OP - 结构化数组的数据需要一个元组或元组列表。
  • 但问题是:你真的想在这里使用结构化数组吗?
  • @norie 确实说过什么。您执行ticker = np.array(raw_ticker[1:]) 之类的操作,然后加载浮点数。您还可以将多个代码加载到例如一个 dict[str, List[relevant datatype]] 并使用 Pandas DataFrames 或 PyArrow Tables 之类的东西来按列组织数据。
  • 先看@norie 的评论。如果值不同,numpy 将尝试使它们相同。例如a = np.array(['1', 2]) 变为['1', '2']

标签: python numpy dtype


【解决方案1】:

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

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'。

【讨论】:

  • 它不适用于'symbol', 'str',但正如您所提到的,它适用于'symbol', 'U20'
猜你喜欢
  • 1970-01-01
  • 2017-04-29
  • 2019-10-31
  • 1970-01-01
  • 1970-01-01
  • 2021-09-24
  • 2021-12-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多