簡體   English   中英

boolean numpy 數組到 char numpy 數組

[英]boolean numpy array to char numpy array

在 c++ 中,有bitset 我可以將 boolean 數組轉換為 int(通過使用 to_ulong)。 我也可以使用 ulong 作為字符緩沖區。
在 python 中什么可以將 boolean 數組轉換為 char 數組? \

具體來說,我有一個 boolean numpy 數組,
對於形狀為 [n, b] 的數組
我想得到 [n, b/8] 形狀數組

現在,我正在通過組合 boolean 創建一個字符數組,但這似乎很慢。

有什么提高速度的好方法嗎?

import numpy as np
def joiner(X):
    return sum(X[:, i] * 2**i for i in range(8))

arr = np.random.randint(0, 2, [100000, 8 * 1024])
cov = np.split(arr, (arr.shape[-1] + 7) // 8, axis = -1)
cov = np.stack(list(map(joiner, cov)), axis = -1)

CPU 時間:用戶 17.5 秒,系統:7.52 秒,總計:25 秒
掛牆時間:25.1 秒

你可以這樣做:

mask = np.array([2**i for i in range(8)])
cov = np.sum(mask * arr.reshape((-1, 8)), axis=1).reshape(arr.shape[0], -1)

生成數據

%%time
import numpy as np
arr = np.random.randint(0, 2, [100000, 8 * 1024], dtype=np.bool_)

CPU 時間:用戶 1.32 秒,系統:1.24 秒,總計:2.55 秒 牆時間:2.14 秒


最快的轉換方法

%%time
cov = sum(arr[i::8] * np.uint8(2**i) for i in range(8))

CPU 時間:用戶 190 毫秒,系統:94.5 毫秒,總計:285 毫秒 牆時間:284 毫秒


@D.Manasreh

%%time
mask = np.array([2**i for i in range(8)])
cov = np.sum(mask * arr.reshape((-1, 8)), axis=1).reshape(arr.shape[0], -1)

CPU 時間:用戶 4.54 秒,系統:9.67 秒,總計:14.2 秒 牆時間:14.7 秒


其他經歷

%%time
cov = arr.reshape(-1, 8) @ (2 ** np.arange(8)).astype(np.uint8)

CPU 時間:用戶 717 毫秒,系統:96 毫秒,總計:813 毫秒 牆時間:811 毫秒

%%time
cov = arr.reshape(-1, 32) @ (2 ** np.arange(32)).astype(np.uint32)

CPU 時間:用戶 918 毫秒,系統:497 毫秒,總計:1.42 秒 牆時間:1.43 秒

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM