Home > front end >  applying a function to a numpy array not working as I expected
applying a function to a numpy array not working as I expected

Time:01-20

>>> ndarr = np.array([0, 1, 2])
>>> (lambda x: x   1) (ndarr)
array([1, 2, 3])

I see that it replaces every element with the function applied to it.

but when I do this to a two dimensional array:

>>> ndarr = np.array([[0, 1, 2], [3, 4, 5]])
>>> (lambda x: x[0]) (ndarr)
array([0, 1, 2])

I thought this would take the two elements of the array which are [0, 1, 2] and [3, 4, 5], apply the lambda to them resulting in 0 and 3, and the result would be [0, 3]. but this applies the function to the whole array instead. why? and wat do I do to get [0, 3]?

CodePudding user response:

Applying 1 on a numpy array will cause all elements to be incremented by one, as you have noticed. However, this does not imply that every operation you perform using a numpy array will be a "mapping". In the second example, there is simply a nested list, and you select the first element of the outer list. The exact same would happen if you just used regular Python:

>>> nlist = [[0, 1, 2], [3, 4, 5]]
>>> (lambda x: x[0]) (nlist)
[0, 1, 2]

You are looking for a mapping if you want to apply an operation on each of the nested arrays. However, this problem can be solved with a slice most easily:

>>> ndarr = np.array([[0, 1, 2], [3, 4, 5]])
>>> ndarr[:,0]
array([0, 3])
  •  Tags:  
  • Related