Python:切片多维数组

时间:2022-02-10 21:27:55

I'm new to Python and numpy. I've figured out how to slice 1 dimensional sequence: arr[start:end], and access an element in the array: el = arr[row][col].

我是Python和numpy的新手。我已经想出如何切割1维序列:arr [start:end],并访问数组中的元素:el = arr [row] [col]。

Trying something like slice = arr[0:2][0:2] (where arr is a numpy array) doesn't give me the first 2 rows and columns, but repeats the first 2 rows. What did I just do, and how do I slice along another dimension?

尝试像slice = arr [0:2] [0:2](其中arr是一个numpy数组)并没有给我前两行和列,但重复前两行。我刚才做了什么,以及如何沿着另一个维度切片?

1 个解决方案

#1


41  

If you use numpy, this is easy:

如果你使用numpy,这很容易:

slice = arr[:2,:2]

or if you want the 0's,

或者如果你想要0,

slice = arr[0:2,0:2]

You'll get the same result.

你会得到相同的结果。

*note that slice is actually the name of a builtin-type. Generally, I would advise giving your object a different "name".

*请注意,切片实际上是内置类型的名称。一般来说,我建议给你的对象一个不同的“名字”。


Another way, if you're working with lists of lists*:

另一种方法,如果你正在使用列表列表*:

slice = [arr[i][0:2] for i in range(0,2)]

(Note that the 0's here are unnecessary: [arr[i][:2] for i in range(2)] would also work.).

(注意这里的0是不必要的:[范围(2)中的i的[arr [i] [:2]]也可以。)。

What I did here is that I take each desired row 1 at a time (arr[i]). I then slice the columns I want out of that row and add it to the list that I'm building.

我在这里做的是我每次都获取每个所需的行1(arr [i])。然后我将我想要的列切出该行并将其添加到我正在构建的列表中。

If you naively try: arr[0:2] You get the first 2 rows which if you then slice again arr[0:2][0:2], you're just slicing the first two rows over again.

如果你天真地尝试:arr [0:2]你获得前两行,如果你再次切片arr [0:2] [0:2],你只需要再切两行。

*This actually works for numpy arrays too, but it will be slow compared to the "native" solution I posted above.

*这实际上也适用于numpy数组,但与我上面发布的“原生”解决方案相比,它会很慢。

#1


41  

If you use numpy, this is easy:

如果你使用numpy,这很容易:

slice = arr[:2,:2]

or if you want the 0's,

或者如果你想要0,

slice = arr[0:2,0:2]

You'll get the same result.

你会得到相同的结果。

*note that slice is actually the name of a builtin-type. Generally, I would advise giving your object a different "name".

*请注意,切片实际上是内置类型的名称。一般来说,我建议给你的对象一个不同的“名字”。


Another way, if you're working with lists of lists*:

另一种方法,如果你正在使用列表列表*:

slice = [arr[i][0:2] for i in range(0,2)]

(Note that the 0's here are unnecessary: [arr[i][:2] for i in range(2)] would also work.).

(注意这里的0是不必要的:[范围(2)中的i的[arr [i] [:2]]也可以。)。

What I did here is that I take each desired row 1 at a time (arr[i]). I then slice the columns I want out of that row and add it to the list that I'm building.

我在这里做的是我每次都获取每个所需的行1(arr [i])。然后我将我想要的列切出该行并将其添加到我正在构建的列表中。

If you naively try: arr[0:2] You get the first 2 rows which if you then slice again arr[0:2][0:2], you're just slicing the first two rows over again.

如果你天真地尝试:arr [0:2]你获得前两行,如果你再次切片arr [0:2] [0:2],你只需要再切两行。

*This actually works for numpy arrays too, but it will be slow compared to the "native" solution I posted above.

*这实际上也适用于numpy数组,但与我上面发布的“原生”解决方案相比,它会很慢。