Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
numpy 2-dimentional
#1
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?
Reply
#2
print(names[0,0],[0,1])
Reply
#3
(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']
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply
#4
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]])
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  [Numpy] How to store different data type in one numpy array? water 7 288 Mar-26-2024, 02:18 PM
Last Post: snippsat
  Numpy returns "TypeError: unsupported operand type(s) for *: 'numpy.ufunc' and 'int'" kalle 2 2,527 Jul-19-2022, 06:31 AM
Last Post: paul18fr
  "erlarge" a numpy-matrix to numpy-array PhysChem 2 2,926 Apr-09-2019, 04:54 PM
Last Post: PhysChem
  Convert element of list to integer(Two dimentional array) zorro_phu 3 4,624 Jun-12-2018, 04:49 AM
Last Post: zorro_phu

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020