蟒:切片一个多维数组 [英] Python: slicing a multi-dimensional array

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

问题描述

我是新来的Python和numpy的。我已经想通了如何切1尺寸:改编[atart:结束] ,并在数组中访问一个元素: EL = ARR [行] [COL]

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

试图像片= ARR [0:2] [0:2] (其中改编是一个numpy的数组)不给我的前2行和列,但重复前2行。什么我就做什么,怎么做我沿着另一个维度切片?

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?

推荐答案

如果您使用 numpy的,这很容易:

If you use numpy, this is easy:

slice = arr[:2,:2]

如果你想要的0,

or if you want the 0's,

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

您会得到相同的结果。

*注:实际上是一个内置式的名称。一般来说,我会建议给你的对象,不同的名字。

*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)]

(注意:0这里是不必要的: [改编[I] [:2]我在范围内(2)] 也将工作)。

我在这里所做的是,我把每所需的行1在时间(改编[I] )。然后,我切我想要的列从该行并将其添加到我建立的名单。

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.

如果你天真地尝试:改编[0:2] 你得到第一个2排它,如果你然后再切改编[0:2 ] [0:2] ,你只是切片一遍又一遍的前两行

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.

*其实,这适用于numpy的阵列也一样,但相比于本土的解决方案我在上面贴吧将是缓慢的。

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

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

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