Reputation: 9
This is my code
L = np.random.choice([-1,1], size = [2,2])
np.putmask(L, L == -1, "+")
print(L)
I get this error invalid literal for int() with base 10: '+'
. Any solution for this problem.
Upvotes: 0
Views: 73
Reputation: 231395
In [227]: np.random.choice([-1,1], size=[2,2])
Out[227]:
array([[ 1, 1],
[-1, 1]])
Change the numbers to strings:
In [229]: x=np.random.choice(["-1","1"], size=[2,2])
In [230]: x
Out[230]:
array([['-1', '1'],
['-1', '-1']], dtype='<U2')
Note the dtype, 'U2'. Now we can replace some of those strings with another string:
In [231]: np.putmask(x,x=="-1", '+')
In [232]: x
Out[232]:
array([['+', '1'],
['+', '+']], dtype='<U2')
I could do string operations on elements of such an array:
In [233]: [''.join(row) for row in x.tolist()]
Out[233]: ['+1', '++']
Upvotes: 0
Reputation: 2428
It looks like you are trying to convert all negative terms to positive.
The issue here is with your use of the 'np.putmask' function
From the documentation example:
>>> x = np.arange(6).reshape(2, 3)
>>> np.putmask(x, x>2, x**2)
>>> x
array([[ 0, 1, 2],
[ 9, 16, 25]])
Hence, for your code to work you should use:
>>>L = np.random.choice([-1,1], size = [2,2])
>>>np.putmask(L, L == -1, np.abs(L))
>>>print(L)
[[1 1]
[1 1]]
Now, if instead, what you actually want is to replace it by the symbol "+" You have to change the dtype of the array.
Since np.random.choice works with a fixed input, it uses the same data type when building the random array! Hence, , you can change it after its built, or change the input, like this:
L = np.random.choice([-1,1], size = [2,2])
L = np.array(L, dtype='object')
np.putmask(L, L == -1, "+")
or like that:
L = np.random.choice(np.array([-1,1],dtype='object'), size = [2,2])
np.putmask(L, L == -1, "+")
print(L)
hope it helps!
Upvotes: 1