簡體   English   中英

基於布爾數組將列插入到numpy數組中

[英]Inserting columns into numpy arrays based on Boolean array

如果這個問題有一個基本的答案,但我還沒有找到答案,我深表歉意。

我有一些數據最初是一個形狀為(N, M)numpy數組,但其中某些列已被刪除。 為了說明,假設M=6和 2 列被刪除,留下(N, 4)數組。 我還有一個數組,表示是否使用布爾值保留列(如果保留則為True否則為False ),例如array([False, True, True, False, True, True])

我想做的是從(N, 4)數組和布爾標記重建(N, 6)數組,並在正確的索引處重新引入列(用零填充)。

對必要的切片等方法的任何幫助都將受到重視!

讓我們試試這個:

# original array -- for references only
arr = np.arange(12).reshape(-1,6)

# keep indexes
keep = np.array([False,  True,  True,  False,  True,  True])

# array after removing the columns
removed_arr = arr[:,keep]

# output array
out = np.zeros((removed_arr.shape[0], len(keep)), dtype=removed_arr.dtype)

# copy the values of `removed_arr` to output
out[:, keep] = removed_arr

輸出:

array([[ 0,  1,  2,  0,  4,  5],
       [ 0,  7,  8,  0, 10, 11]])

暫無
暫無

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

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