python - 列表到 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'
我没有得到,因为我明确指定该字段是字符串,而不是浮点数。
解决方案
以元组或元组列表的形式提供数据:
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'。
推荐阅读
- python - 将输出写入不同的 csv 文件列
- python - 从 numpy 数组在 PyQt5 中显示图像
- python - 如何修复 sklearn for python 安装失败
- android-studio - 在 Google Play 商店中上传 Ionic 项目的错误
- python - 尝试创建 Twitter 情绪分析,我收到此错误 AttributeError: 'str' object has no attribute 'csv'
- python - 在 Pandas 列中过滤列表中的项目
- r - 使用R中的函数从服务器下载数据时利用for循环?
- go - 使用反射的接口的指针接收器更新函数中结构的字段
- java - 我应该在 android studio 中为类似的回收器视图编写多个适配器吗?
- regex - 用于零件号查找的正则表达式