gpt4 book ai didi

python - 根据给定的位信息提取 Numpy 数组的索引

转载 作者:太空宇宙 更新时间:2023-11-04 10:31:09 25 4
gpt4 key购买 nike

我的数据是'32位无符号整数'的形式如下:

myData = np.array([1073741824, 1073741877, 1073742657, 1073742709, 1073742723, 1073755137, 1073755189,1073755969],dtype=np.uint32)

我想获取发生以下情况的“myData”元素的索引:

Bit No. 0–1
Bit Combination: 00

我该怎么做?

最佳答案

您可以使用 np.binary_repr() 获取表示每个元素的字符串,并从该字符串中获取符合您的条件的元素:

end = `00`
s = [np.binary_repr(ai, width=len(end)) for ai in myData]
indices = [i for (i, si) in enumerate(s) if si.endswith(end)]

编辑:矢量化(和推荐)方法

进一步研究后,我发现在使用数组的 uint8 View 后,您可以使用 np.unpackbits():

myData = myData.view(np.uint32) # not needed if it is already np.uint32
tmp = np.unpackbits(myData.view(np.uint8)[::4][None, :], axis=0)
indices = np.where((tmp[-2, :] == 0) & (tmp[-1, :] == 0))[0]

请注意,切片是根据您正在比较的位进行的:

  • [::4] 前 8 位
  • [1::4] 第 9 位到第 16 位
  • [2::4]为第17位到第24位
  • [3::4]第25位到第32位

例如,如果您的原始数据类型是 np.uint64,则此序列可以继续下去,但在这种情况下使用 [n::8] 代替。

关于python - 根据给定的位信息提取 Numpy 数组的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26436705/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com