I can't really understand why my code isn't working, see:
import numpy as np
def round2c(x):
for i in x:
for j in i:
if (j >= 0 and j<= 0.33):
j = 0
else:
j = 1
return x
list = [[0.05,0.1,0.4],[0.5,0.5,0.3]]
list2 = round2c(list)
print(list2)
a = np.array([[0.05,0.1,0.4],[0.5,0.5,0.3]])
b = round2c(a)
print(b)
It's neither working with a np.ndarray nor with a list. What am I doing wrong?
CodePudding user response:
I think your problem is the assigment of variables, check the following is working.
import numpy as np
def round2c(x):
for num1, i in enumerate(x):
for num2, j in enumerate(i):
if (0 <= j<= 0.33):
i[num2] = 0
else:
i[num2] = 1
x[num1] = i
return x
list1 = [[0.05,0.1,0.4],[0.5,0.5,0.3]]
list2 = round2c(list)
print(list2)
a = np.array([[0.05,0.1,0.4],[0.5,0.5,0.3]])
b = round2c(a)
print(b)
output:
[[0, 0, 1], [1, 1, 0]]
[[0. 0. 1.]
[1. 1. 0.]]
CodePudding user response:
If your goal is to binarize the numbers, numpy arrays has the method digitize which achieves what your code does without creating a function yourself.
list1 = [[0.05,0.1,0.4], [0.5,0.5,0.3]]
list1 = np.array(list1)
# bins contains the numbers that separates the values in the list
# right is False since 0.33 is included in the left interval
list2 = np.digitize(list1, bins=[0.33], right=False)
print(list2)
The docs for the binarize method is in this link.