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

Python-Numpy-将十六进制字符串的Numpy数组转换为整数,python,numpy,Python,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)])

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

有更好的方法吗?

使用列表理解:

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

[9, 10, 11]
使用地图的备选方案:

导入工具
列表(映射(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)
intArray=[int(hexNum,16)表示列表中的hexNum(hexArray)]

尝试此操作,使用列表理解将每个十六进制数转换为整数。

是否存在等于或大于10的数字字符串?还有,顺便问一下,你在找什么?紧凑还是性能更高?@Divakar我希望它转换所需的时间最少。这个例子只有几个值,但我会有1000个值的数组。
hexArray=np.array(['9','a','1B'])
其中
1B
-->
27
使用这个代码我会得到输出
数组([9,208,10,208,1,11],dtype=uint8)
。如何让它对任何值工作,而不仅仅是对1,2,3,4,5,6,7,8,9,a,b,c,d,e,f@Ch3steR那是我的,没有回应,而且因为标题有
hex
字符串,我假设它都是一个字符串。我想如果他们也有这样的情况,OP会回来的。我不是说这个答案不好或是抱怨。我只是想知道如何将每个十六进制字符串转换为int。@Ch3steR我没想到你是。对于这一点,我们需要进一步处理
v
,这将不是很好。