I am trying to see if each value in array is less then 0 then output 0, else output the number itself. The output must have the same dimensions as the input. Currently the input is a 3 by 4 but output is a list. How do I get the output size the same (3 by 4 array)?
JavaScript
x
10
10
1
input = [[1,2,3,4],[4,5,-6,-7],[8,9,10,11]]
2
output= []
3
for i in input:
4
if i < 0:
5
value = 0
6
output.append(value)
7
else:
8
value= i
9
output.append(value)
10
Advertisement
Answer
Python’s NumPy arrays are a much more efficient way of dealing with matrices, which are what you have if all of your nested lists are the same size. If I understood your question, your example can be simplified down to a single line:
JavaScript
1
12
12
1
import numpy as np
2
inp = np.array([[-1,2,3,4],[4,5,-6,7],[8,9,-10,11]])
3
print (inp)
4
#[[ -1 2 3 4]
5
# [ 4 5 -6 7]
6
# [ 8 9 -10 11]]
7
inp[inp < 0] = 0
8
print (inp)
9
# [[ 0 2 3 4]
10
# [ 4 5 0 7]
11
# [ 8 9 0 11]]
12