简体   繁体   English

访问np.array的部分

[英]accessing portions of np.array

I want to have quick access to np.array elements for example from indexes from 0-6 plus 10 to the end. 我想快速访问np.array元素,例如从0-6加10到最后的索引。 So far I have tried: 到目前为止,我已经尝试过:

a[0:6,10:]

or 要么

np.concatenate(a[0:6],a[10:])

both are giving me error, with the second one giving me:"TypeError: only integer scalar arrays can be converted to a scalar index" 两者都给我错误,第二个给我错误:“ TypeError:只有整数标量数组可以转换为标量索引”

Edit: concatenate is still giving me problems, so I am going to post my full code here: 编辑:串联仍然给我问题,所以我要在这里发布我的完整代码:

Fold_5 = len(predictorX)/5
trainX = np.concatenate(predictorX[:3*int(Fold_5)],predictorX[4*int(Fold_5)])

predictor X is an array with values like 预测变量X是一个数组,其值类似于

[[0.1,0.4,0.6,0.2],[..]....]

Here are two more short ways of getting the desired subarray: 这是获取所需子数组的另外两种简短方法:

np.delete(a, np.s_[6:10])

and

np.r_[a[:6], a[10:]]

In: 在:

a[0:6,10:]

0:6 selects rows, 10: selects columns. 0:6选择行,10:选择列。 If a isn't 2d or large enough that will result in an error. 如果a不为2d或足够大,则将导致错误。

In

np.concatenate(a[0:6],a[10:])

the problem is the number of arguments; 问题是参数的数量; it takes a list of arrays. 它需要一个数组列表。 A second one, if given is understood to be axis , which should be an integer (hence your error). 如果给出第二个,则将其理解为axis ,它应该是整数(因此会出错)。

np.concatenate([a[0:6],a[10:]])

should work. 应该管用。

Another option is to index with a list 另一种选择是使用列表编制索引

a[0,1,2,3,4,5,10,11,...]]

np.r_ is a handy little tool for constructing such a list: np.r_是构造此类列表的便捷小工具:

In [73]: np.r_[0:6, 10:15]
Out[73]: array([ 0,  1,  2,  3,  4,  5, 10, 11, 12, 13, 14])

It in effect does np.concatenate([np.arange(0,6),np.arange(10,15)]) . 它实际上执行np.concatenate([np.arange(0,6),np.arange(10,15)])

It doesn't matter whether you index first and the concatenate, or concatenate indexes first and then index. 无论先索引然后连接,还是先索引然后索引都没有关系。 Efficiency is about the same. 效率差不多。 np.delete chooses among several methods, including these, depending on the size and type of the 'delete' region. np.delete取决于“ delete”区域的大小和类型,在几种方法中进行选择。

In the trainX expression adding [] to the concatenate call should work. trainX表达式中, trainX []添加到串联调用中。 However, predictorX[4*Fold_5] could be a problem. 但是, predictorX[4*Fold_5]可能是个问题。 Are you missing a : (as in 10: example)? 是否缺少: (在10:为例)? If you want just one value, then you need to convert it to 1d, eg predictorX[[4*Fold_5]] 如果只需要一个值,则需要将其转换为1d,例如: predictorX[[4*Fold_5]]

Fold_5 = len(predictorX)//5   # integer division in py3
trainX = np.concatenate([predictorX[:3*Fold_5], predictorX[4*Fold_5:]])

np.concatenate takes a sequence of arrays. np.concatenate需要一个数组序列。 try 尝试

np.concatenate([a[0:6],a[10:]])

or 要么

np.concatenate((a[0:6],a[10:]))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM