python - Python - Numpy - 将 numpy 十六进制字符串数组转换为整数
问题描述
我有一个 numpy 十六进制字符串数组(例如:['9','A','B']),并希望将它们全部转换为 0 255 之间的整数。我知道如何做到这一点的唯一方法是使用 for循环并附加一个单独的 numpy 数组。
import numpy as np
hexArray = np.array(['9', 'A', 'B'])
intArray = np.array([])
for value in hexArray:
intArray = np.append(intArray, [int(value, 16)])
print(intArray) # output: [ 9. 10. 11.]
有一个更好的方法吗?
解决方案
具有数组视图功能的矢量化方式 -
In [65]: v = hexArray.view(np.uint8)[::4]
In [66]: np.where(v>64,v-55,v-48)
Out[66]: array([ 9, 10, 11], dtype=uint8)
计时
给定样本的设置按比例放大1000x
-
In [75]: hexArray = np.array(['9', 'A', 'B'])
In [76]: hexArray = np.tile(hexArray,1000)
# @tianlinhe's soln
In [77]: %timeit [int(value, 16) for value in hexArray]
1.08 ms ± 5.67 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
# @FBruzzesi soln
In [78]: %timeit list(map(functools.partial(int, base=16), hexArray))
1.5 ms ± 40.5 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
# From this post
In [79]: %%timeit
...: v = hexArray.view(np.uint8)[::4]
...: np.where(v>64,v-55,v-48)
15.9 µs ± 294 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
推荐阅读
- python - 收到错误“找不到名称为“开始”的关键字。” 在使用机器人框架运行 sikuliLibrary 时
- python - 将列表(元组)列表转换为熊猫中的长数据框
- php - 警告:PDOStatement::execute():
- javascript - 如何动态上传和运行javascript文件?
- unit-testing - 如何使用 Moq 模拟 IDocumentClient?
- javascript - 嵌入来自 tiktok 的视频
- mysql - 请将此 Sql 查询转换为 Postgresql
- java - 范围报告 TestRunner 日志视图:它是从版本 4 中删除还是我们可以启用?
- iocp - 在windows的多线程中使用IOCP时如何确保线程安全?
- algorithm - 由数组的子数组组成的多项式的乘积