0

I'm quite new to python and I'm working on some data manipulation. I thought the indexing in numpy would be [row][column], but it's not what I see when I execute in python. Below is a simple example of how python is behaving. I don't understand why I get the same results for the last two commands:

import numpy as num

test_arr = num.array([[1, 2, 3],[4, 5, 6], [7, 8, 9]],dtype=num.float32)

test_arr[0][:]
array([1., 2., 3.], dtype=float32)

test_arr[:][0]
array([1., 2., 3.], dtype=float32)

I would expect

test_arr[0][:]
array([1., 2., 3.], dtype=float32)

test_arr[:][0]
array([1., 4., 7.], dtype=float32)

Can someone explain why python behaves as it does and how to get the 0th index of all rows?

1
  • Even with Python lists [:] only creates a copy; with arrays it's a view. So it's doing nothing in your examples. Each [] is a separate indexing step. Take time to read numpy basics, such as this indexing page: docs.scipy.org/doc/numpy/reference/arrays.indexing.html Commented Apr 2, 2020 at 15:52

2 Answers 2

1

to get a column in numpy array use [:,n] where n is your column number

test_arr[:,0]
array([1., 4., 7.], dtype=float32)
Sign up to request clarification or add additional context in comments.

Comments

0
In  : import numpy as num

In  : test_arr = num.array([[1, 2, 3],[4, 5, 6], [7, 8, 9]],dtype=num.float32)

In  : test_arr[0,:]
Out : [1. 2. 3.]

In  : test_arr[:,0]
Out : [1. 4. 7.]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.