英文:
How to set dtype in np.asarray?
问题
list_t = [['微信', '61860', '63409', '-1549'],
['支付宝', '121990', '112995', '9239'],
['腾讯视频', '116221', '106665', '7955'],
['讯飞语音引擎', '350777', '325049', '51728'],
['百度', '140252', '108637', '32015'],
['抖音短视频', '118262', '150556', '31706'],
['QQ', '118878', '104456', '14452'],
['高德地图', '95748', '82388', '12685'],
['手机淘宝', '148342', '135533', '12519'],
['拼多多', '335259', '224793', '111166']]
dt = np.dtype([("a","U7"),("b","i4"),("c","i4"),("d","i4")])
array_t = np.asarray(list_t, dtype=dt)
英文:
list_t = [['微信', '61860', '63409', '-1549'],
['支付宝', '121990', '112995', '9239'],
['腾讯视频', '116221', '106665', '7955'],
['讯飞语音引擎', '350777', '325049', '51728'],
['百度', '140252', '108637', '32015'],
['抖音短视频', '118262', '150556', '31706'],
['QQ', '118878', '104456', '14452'],
['高德地图', '95748', '82388', '12685'],
['手机淘宝', '148342', '135533', '12519'],
['拼多多', '335259', '224793', '111166']]
dt = np.dtype([("a","U7"),("b","i4"),("c","i4"),("d","i4")])
array_t = np.asarray(list_t, dtype=dt)
ValueError: invalid literal for int() with base 10: '微信'
答案1
得分: 0
要创建一个结构化数组,与结构化元素关联的值必须存储为元组,而不是列表:
In [62]: array_t = np.asarray([tuple(row) for row in list_t], dtype=dt)
In [63]: array_t
Out[63]:
array([('微信', 61860, 63409, -1549), ('支付宝', 121990, 112995, 9239),
('腾讯视频', 116221, 106665, 7955),
('讯飞语音引擎', 350777, 325049, 51728), ('百度', 140252, 108637, 32015),
('抖音短视频', 118262, 150556, 31706), ('QQ', 118878, 104456, 14452),
('高德地图', 95748, 82388, 12685), ('手机淘宝', 148342, 135533, 12519),
('拼多多', 335259, 224793, 111166)],
dtype=[('a', '<U7'), ('b', '<i4'), ('c', '<i4'), ('d', '<i4')])
英文:
To create a structured array, the values associated with a structured element must be stored as tuples, not lists:
In [62]: array_t = np.asarray([tuple(row) for row in list_t], dtype=dt)
In [63]: array_t
Out[63]:
array([('微信', 61860, 63409, -1549), ('支付宝', 121990, 112995, 9239),
('腾讯视频', 116221, 106665, 7955),
('讯飞语音引擎', 350777, 325049, 51728), ('百度', 140252, 108637, 32015),
('抖音短视频', 118262, 150556, 31706), ('QQ', 118878, 104456, 14452),
('高德地图', 95748, 82388, 12685), ('手机淘宝', 148342, 135533, 12519),
('拼多多', 335259, 224793, 111166)],
dtype=[('a', '<U7'), ('b', '<i4'), ('c', '<i4'), ('d', '<i4')])
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论