gpt4 book ai didi

将带符号的 int32 列表转换为二进制/ bool numpy 数组的 Pythonic 方法

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

是否有更好(更有效和/或可读)的方法将带符号的 int32 转换为转置二进制/ bool numpy 数组?

This example is a simplification. fp can have almost 1,000 elements

这是我目前所拥有的(使用 Python 2.7):

fp = [-15707075, -284140225]
np.transpose(np.array([[b == '1' for b in list('{:32b}'.format(i & 0xffffffff))] for i in fp]))

结果:

[[ True  True]
[ True True]
[ True True]
[ True False]
[ True True]
[ True True]
[ True True]
[ True True]
[False False]
[False False]
[False False]
[ True True]
[False False]
[False False]
[False False]
[False False]
[False False]
[ True True]
[False False]
[ True True]
[False True]
[ True True]
[False False]
[False True]
[False False]
[False False]
[ True True]
[ True True]
[ True True]
[ True True]
[False True]
[ True True]]

最佳答案

使用 numpy.unpackbits如果 fp 是一个大的 NumPy 数组,速度会更快:

(np.unpackbits(fp.astype('>i4').view('4,uint8'), axis=1).T.astype(bool))

astype('>i4')fp 转换为大端 32 位整数数组,然后view('4,uint8') View (或者,您可能会说重新解释)32 位整数为四个 8 位整数。这样做是因为 unpackbits 需要一个数组无符号 8 位整数。大端格式用于确保最重要的位在左边——这样排列值,所以 np.unpackbits 返回所需顺序的位。

In [280]: fp = np.array([-15707075, -284140225])

In [281]: fp.astype('>i4').view('4,uint8')
Out[281]:
array([[255, 16, 84, 61],
[239, 16, 93, 63]], dtype=uint8)

In [282]: np.unpackbits(fp.astype('>i4').view('4,uint8'), axis=1)
Out[282]:
array([[1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1,
0, 0, 0, 0, 1, 1, 1, 1, 0, 1],
[1, 1, 1, 0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1,
0, 1, 0, 0, 1, 1, 1, 1, 1, 1]], dtype=uint8)

import numpy as np

fp = np.array([-15707075, -284140225])
expected = (np.transpose(np.array([[b == '1' for b in list('{:32b}'.format(i & 0xffffffff))] for i in fp])))

result = (np.unpackbits(fp.astype('>i4').view('4,uint8'), axis=1).T.astype(bool))

assert (expected == result).all()

对于大小为 100 的数组,使用 np.unpackbits 大约快 72 倍(在我的机器上)。速度优势随 fp 的长度增加:

In [241]: fp = np.random.random(size=100).view('int32')

In [276]: %timeit expected = (np.transpose(np.array([[b == '1' for b in list('{:32b}'.format(i & 0xffffffff))] for i in fp])))
100 loops, best of 3: 2.22 ms per loop

In [277]: %timeit result = (np.unpackbits(fp.astype('>i4').view('4,uint8'), axis=1).T.astype(bool))
10000 loops, best of 3: 30.6 µs per loop

关于将带符号的 int32 列表转换为二进制/ bool numpy 数组的 Pythonic 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46107996/

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