2
votes

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()

3
What would you expect the answer to np.array([[-0.5, 0.2, 0.0], [4.2, 3.14, -2.7]]) < 0 to be? Python doesn't know how to handle that kind of comparison.all or None
Try to compare A < 0. This makes no sense. I think you want smth like B = [assign(a) for a in x for x in A] or anything else.sashaaero
A<0 produces a boolean array the same size as A. Python if only works with a scalar boolean True/False. It's a simple either/or action. It can't work with multiple boolean values.hpaulj
Thank you. i implemented using clip and np.sign()py_newbie
Note, the lambda function is not really relevant. In any case, if you are going to assign your anonymous function to a name, you should just use a regular function definition.juanpa.arrivillaga

3 Answers

3
votes

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.

1
votes

You can use the lambda, but the numpy datatypes allow you to do many "matlab-type" operations (for those who are used to that):

  • python:

    a = np.array([1, 2, 3, 4, 5])
    ((a > 1) & (a < 3)).astype(int)
    # array([0, 1, 0, 0, 0])
    
  • octave/matlab

    a = [1,2,3,4,5];
    a>1 & a<3
    % ans =
    %
    %  0  1  0  0  0
    
0
votes

This worked for me:

A = A.clip(min=0, max=1)