简体   繁体   English

访问Numpy数组中四个元素的最快方法?

[英]Fastest way to access middle four elements in Numpy array?

Suppose I have a Numpy array, such as假设我有一个 Numpy 数组,例如

rand = np.random.randn(6, 6)

I need the central four values in the array, since it has axes of even length.我需要数组中的四个中心值,因为它具有偶数长度的轴。 If it had been odd, such as 5 by 5, then there would only be one central value.如果它是奇数,例如 5 x 5,那么将只有一个中心值。 What is the simplest/fastest/easiest way of retrieving these four entries?检索这四个条目的最简单/最快/最简单的方法是什么? I can obtain them very crudely with indices, but I'm looking for a faster way than calling a bunch of functions and performing a bunch of calculations.我可以用索引非常粗略地获得它们,但我正在寻找一种比调用一堆函数和执行一堆计算更快的方法。

For example, consider the following:例如,请考虑以下情况:

array([[ 0.25659355, -0.75456113,  0.39467396,  0.50805361],
       [-0.77218172,  1.00016061, -0.70389486,  1.67632146],
       [-0.41106158, -0.63757421,  1.70390504, -0.79073362],
       [-0.2016959 ,  0.55316318, -1.55280823,  0.45740193]])

I want the following:我想要以下内容:

array([[1.00016061, -0.70389486],
       [-0.63757421,  1.70390504]])

But not just for a 4 by 4 array - if it is even by even, I want the central four elements, as above.但不仅仅是对于 4 x 4 数组 - 如果它是偶数,我想要中央四个元素,如上所述。

Is something like this too complicated?这样的事情是不是太复杂了?

def get_middle(arr):
    n = arr.shape[0] / 2.0
    n_int = int(n)
    if n % 2 == 1:
        return arr[[n_int], [n_int]]
    else:
        return arr[n_int:n_int + 2, n_int:n_int + 2]

You can do this with a single slicing operation:您可以使用单个切片操作来完成此操作:

rand = np.random.randn(n,n)
# assuming n is even
center = rand[n/2-1:n/2+1, n/2-1:n/2+1]

I'm abusing order of operations by leaving out the parens, just to make it a little less messy.我通过省略括号来滥用操作顺序,只是为了让它不那么混乱。

Given array a:给定数组 a:

 import numpy as np a = np.array([[ 0.25659355, -0.75456113, 0.39467396, 0.50805361], [-0.77218172, 1.00016061, -0.70389486, 1.67632146], [-0.41106158, -0.63757421, 1.70390504, -0.79073362], [-0.2016959 , 0.55316318, -1.55280823, 0.45740193]])

The easiest way to get the central 4 values is:获得中心 4 个值的最简单方法是:

 ax, ay = a.shape a[int(ax/2)-1:int(ax/2)+1, int(ay/2)-1:int(ay/2)+1]

This works if you have even numbers for the dimensions of the array.如果数组的维度有偶数,则此方法有效。 In case of odd numbers, there won't be a central 4 values.在奇数的情况下,不会有中央 4 值。

Could you just use indexing?你可以只使用索引吗? Like:像:

A = np.array([[ 0.25659355, -0.75456113,  0.39467396,  0.50805361],
[-0.77218172,  1.00016061, -0.70389486,  1.67632146],
[-0.41106158, -0.63757421,  1.70390504, -0.79073362],
[-0.2016959 ,  0.55316318, -1.55280823,  0.45740193]])
])

A[1:3,1:3]

Or if matrix A had odd dimensions, say 5x5 then:或者,如果矩阵 A 具有奇数维度,例如 5x5,则:

A[2,2]

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

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