有一个名为"target_y"
的一维numpy
数组。我的任务是在执行逻辑回归之前,确保"target_y"
的所有值都编码为1
和-1
,而不是1
和0
。一旦我完成了,我需要将其分配给"prepared_y"
并返回。我可以写一些类似的东西吗:
if target_y in 1,-1:
prepared_y = target_y
要用numpy.array
中的-1
替换所有0
值,简单如下:
a[a == 0] = -1
其中CCD_ 12是一维阵列。
结账np.all
:
我们可以做一些快速的布尔运算来检查所有的值是1
还是-1
:
if np.all((target_y == 1) + (target_y == -1)): # checks if the array has all 1s and -1s
prepared_y = target_y
如果要将所有0
秒更改为-1
秒,请为所有0
秒切片:
target_y[np.argwhere(target_y == 0)] = -1
对于列表,您可以执行以下操作:
def convert( l ):
return [ -1 if e == 0 else e for e in l ]
对于numpy array
def convert( l ):
return l[ l == 0 ] = -1
if语句可以检查一个值,例如:
if 0 in test_list:
return test_list
准确地说,你需要一个循环来检查每个值:
def list_checker(test_list):
for i, num in enumerate(test_list):
if num == 0:
test_list[i] = -1
return test_list