蟒蛇numpy的数组切片 [英] python numpy array slicing

查看:180
本文介绍了蟒蛇numpy的数组切片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个二维数组,A是6×6。我想先取2的值(指数0,0和0,1),并采取了二者的平均值,平均插入到一个新的数组索引0,0 A(6X3)的列大小的一半。然后,我将在获得下两个指标,平均需要投入新的数组在0.1。

I have an 2d array, A that is 6x6. I would like to take the first 2 values (index 0,0 and 0,1) and take the average of the two and insert the average into a new array that is half the column size of A (6x3) at index 0,0. Then i would get the next two indexes at A, take average and put into the new array at 0,1.

我知道该怎么做,这是使用双循环的唯一方法,但是对于性能的目的(我将使用数组一样大3000x3000)我知道有一个更好的解决方案在那里!谢谢!

The only way I know how to do this is using a double for loop, but for performance purposes (I will be using arrays as big as 3000x3000) I know there is a better solution out there! Thanks!

推荐答案

numpy的数组的一个非常有用的功能是,它们可以被重新塑造,在许多不同的方式观看,并通过这样做,可以使某些操作非常容易。

A very useful feature of numpy arrays is that they can be reshaped and viewed in many different ways, and by doing so, you can make certain operations very easy.

由于要配对每两个项目,是有意义的6x6的阵列重塑成一个18×2数组:

Since you want to pair every two items, it makes sense to reshape the 6x6 array into a 18x2 array:

import numpy as np

arr=np.arange(36).reshape(6,6)
print(arr)
# [[ 0  1  2  3  4  5]
#  [ 6  7  8  9 10 11]
#  [12 13 14 15 16 17]
#  [18 19 20 21 22 23]
#  [24 25 26 27 28 29]
#  [30 31 32 33 34 35]]
arr2=arr.reshape(-1,2)
print(arr2)
# [[ 0  1]
#  [ 2  3]
#  [ 4  5]
#  [ 6  7]
#  [ 8  9]
#  [10 11]
#  [12 13]
#  [14 15]
#  [16 17]
#  [18 19]
#  [20 21]
#  [22 23]
#  [24 25]
#  [26 27]
#  [28 29]
#  [30 31]
#  [32 33]
#  [34 35]]

现在取平均值很简单:

means=arr2.mean(axis=1)
print(means)
# [  0.5   2.5   4.5   6.5   8.5  10.5  12.5  14.5  16.5  18.5  20.5  22.5
#   24.5  26.5  28.5  30.5  32.5  34.5]

最后,我们只是重塑阵列是6X3:

And finally, we just reshape the array to be 6x3:

means=means.reshape(6,-1)
print(means)
# [[  0.5   2.5   4.5]
#  [  6.5   8.5  10.5]
#  [ 12.5  14.5  16.5]
#  [ 18.5  20.5  22.5]
#  [ 24.5  26.5  28.5]
#  [ 30.5  32.5  34.5]]

或者,作为1衬

means=arr.reshape(-1,2).mean(axis=1).reshape(6,-1)

PS:整形是一个非常快的操作,因为它返回一个视图,而不是原始数组的副本。该被改变的所有是尺寸和进展。剩下的就是一个调用的的意思是方法。因此,这一解决方案应该是大约一个快速尽可能使用numpy的

PS: reshaping is a very quick operation, since it is returning a view, not a copy of the original array. All that is changed is the dimensions and the strides. All that remains is one call to the mean method. Thus, this solution should be about a quick as possible using numpy.

这篇关于蟒蛇numpy的数组切片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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