Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

lambda function on a numpy array. What's wrong with this piece of code?

What's wrong with this code :

import numpy as np

A = np.array([[-0.5, 0.2, 0.0],
          [4.2, 3.14, -2.7]])

asign = lambda t: 0 if t<0 else 1
asign(A)
print(A)

expected out:

     [[0.  1.  0.]
      [ 1.  1. 0.]]

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

like image 889
py_newbie Avatar asked Nov 15 '25 10:11

py_newbie


1 Answers

Well the lambda on its own will not go through the whole array. For that you will need a higher order function. In this case: map.

A = np.array([[-0.5, 0.2, 0.0],
              [4.2, 3.14, -2.7]])

asign = lambda t: 0 if t<0 else 1
A = list(map(asign, A))

Map will iterate through every element and pass it through the function. I wrapped map in a list because it returns an object of type map but you can convert it that way.

like image 76
Khepu Avatar answered Nov 17 '25 08:11

Khepu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!