繁体   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