Python Forum

Full Version: numpy 2-dimentional
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I am trying to learn numpy and I am trying to print some data as shown below:

import numpy as np

names = np.array([["Rami", "Taher", "Wahdan"],["First", "Middle", "Last"]])
print(names[[0,0],[1,0]])
The output I am getting is:
Output:
['Taher' 'Rami']
But it should show:
Output:
['Rami' 'First']
What did I do wrong?
print(names[0,0],[0,1])
(Sep-11-2021, 04:54 PM)rwahdan Wrote: [ -> ]What did I do wrong?

I don't know what you did wrong, but you (probably accidentally) used advanced indexing. This means that first list gives rows indices and second gives columns indices in corresponding rows.

If you want to get desired output using advanced indexing then give row in first list and columns in second:

>>> print(names[[0,0],[0,1]])   
['Rami' 'Taher']
What's happening is kind of interesting. You inadvertently used a feature called Integer array indexing. According to the docs:
Quote:Integer array indexing allows selection of arbitrary items in the array based on their N-dimensional index. Each integer array represents a number of indexes into that dimension.
Hopefully this example is a little less confusing.
import numpy as np

names = np.array([["A", "B", "C", "D"],["0", "1", "2", "3"]])

x = np.array([names[1][2], names[0][3]])
print('x', type(x), x)

y = names[[1, 0], [2, 3]]
print('y', type(y), y)
Output:
x <class 'numpy.ndarray'> ['2' 'D'] y <class 'numpy.ndarray'> ['2' 'D']
This shows two ways to make the same numpy array. x uses 2D array indexing like you are used to in C, or can used with 2D Python lists. y uses integer array indexing to get the same result.
names = np.array([["Rami", "Taher", "Wahdan"],["First", "Middle", "Last"]])
print(names[[0,0],[1,0]])
Your example is using integer array indexing to make the same np array as np.array([names[0][1], names[0][0]])