首页 > 解决方案 > 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.]

有一个更好的方法吗?

标签: pythonnumpy

解决方案


具有数组视图功能的矢量化方式 -

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)

推荐阅读