Python Numpy将十六进制字符串的Numpy数组转换为整数

2024-09-29 06:35:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个十六进制字符串的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.]

有更好的方法吗


Tags: 方法字符串inimportnumpyforvalueas
3条回答

使用地图的备选方案:

import functools

list(map(functools.partial(int, base=16), hexArray))
[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)

使用列表理解:

 array1=[int(value, 16) for value in hexArray]
 print (array1)

输出:

[9, 10, 11]

相关问题 更多 >