使用布尔索引复制或查看numpy子数组 [英] Copy or view numpy subarray using boolean indexing

查看:183
本文介绍了使用布尔索引复制或查看numpy子数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出2D numpy数组,即;

Given a 2D numpy array, i.e.;

import numpy as np

data = np.array([
     [11,12,13],
     [21,22,23],
     [31,32,33],
     [41,42,43],         
     ])

我需要基于所需行和列的两个屏蔽向量来创建一个新的子数组或修改所选元素;

I need to both create a new sub-array or modify the selected elements in place based on two masking vectors for the desired rows and columns;

rows = [False, False, True, True]
cols = [True, True, False]

如此

print subArray

# [[31 32]
#  [41 42]]

推荐答案

首先,确保您的rowscols实际上是布尔型ndarrays,然后使用它们为数据建立索引

First, make sure that your rows and cols are actually boolean ndarrays, then use them to index your data

rows = np.array([False, False, True, True], dtype=bool)
cols = np.array([True, True, False], dtype=bool)
data[rows][:,cols]

说明 如果您使用布尔值的 list 而不是 ndarray ,则numpy会将False/True转换为0/1,并将其解释为行/列的索引你要.使用布尔ndarray时,实际上是在使用某些特定的NumPy机制.

Explanation If you use a list of booleans instead of an ndarray, numpy will convert the False/True as 0/1, and interpret that as indices of the rows/cols you want. When using a bool ndarray, you're actually using some specific NumPy mechanisms.

这篇关于使用布尔索引复制或查看numpy子数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆