Rubini
Rubini

Reputation: 25

How to do the below operation in numpy python

I have created an array using numpy:

from numpy import *

a=array([[1,2,3,4,2,7,5,3,8],
         [5,6,7,1,3,6,3,2,8]])

But I dont understand the last one which gives output 7.Could anyone give an explanation??

Upvotes: 0

Views: 61

Answers (2)

Alb
Alb

Reputation: 1330

Let's look at the indices. First you got 1:4:1, which means "From position of index 1 until (non-including) position of index 4, at steps of 1. When you add positions outside of the axis shape to a slicing operation, it will add every position until the last possible one, which because your row axis is sized 2, is only index position one. So, the first indexing is in practice the span of rows 1:. So this is a span of 1 row.

Now the second indexing operation 2:4:2, means "From position of index 2 until (non-including) position of index 4, at steps of 2. Because the step is 2, it will be taking a span of columns including only one column, which is column 2.

The two indexing operations operate over a span of rows and columns, but a span that includes only one row and one column. And what is the representation of an array with one row and one column? It is precisely [[x]]. In your case, x=7 because at row indexed 1 and col indexed 2 you have value 7

The trick is that using the : selects a span (called a slice in python terms) in that axis. That is why when you want to select an index i and eliminate its axis, you select with [i], while when you want to preserve the axis you use [i:i+1]

Upvotes: 0

Josef Brandt
Josef Brandt

Reputation: 63

Well, what you do is a bit strange... Generally spoken, when you index with [a:b:c, d:e:f] you access rows a till b (exclusive) by taking each c'th row. And then from that columns d to e (exclusive), every f'th column.

So, in your last example, you take rows with index 1, 2, 3 and columns with index 2. As your input array only has two rows (i.e. with indices 0 and 1) it only gives you back the element at row index 1 (2nd row) and column index 2 (3rd column). That is the seven.

Iam actually amazed that numpy even gives you a valid return array even if you try to access row indices that do not exists.

And, by the way, it is convention to do the numpy import as "import numpy as np". Technically it does not matter and you can import it as you want, but if you stick to conventions your code is better comprehensible by others and it's easier for you to implement code from others that used the np convention.

Upvotes: 1

Related Questions