简体   繁体   English

基于布尔数组将列插入到numpy数组中

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

Apologies if this question has an elementary answer, but I have not been able to find one yet.如果这个问题有一个基本的答案,但我还没有找到答案,我深表歉意。

I have some data that was originally a numpy array of shape (N, M) , but where certain columns have then been removed.我有一些数据最初是一个形状为(N, M)numpy数组,但其中某些列已被删除。 For illustration lets say M=6 and 2 columns where removed, leaving a (N, 4) array.为了说明,假设M=6和 2 列被删除,留下(N, 4)数组。 What I also have is an array denoting whether a column was kept or not with a Boolean value ( True if kept, False if not), eg array([False, True, True, False, True, True]) .我还有一个数组,表示是否使用布尔值保留列(如果保留则为True否则为False ),例如array([False, True, True, False, True, True])

What I would like to do would be to reconstruct an (N, 6) array from the (N, 4) array and the boolean markers, with the columns reintroduced at the right index (filled with zeros).我想做的是从(N, 4)数组和布尔标记重建(N, 6)数组,并在正确的索引处重新引入列(用零填充)。

Any help on the requisite slicing etc approaches would be valued!对必要的切片等方法的任何帮助都将受到重视!

Let's try this:让我们试试这个:

# 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

Output:输出:

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