你好,我有一个numpy数组,如下所示:
list_of_values = [-0.5, -0.8, -0.6, -0.2, 0.2, 0.5, 0.7, 0.9, -0.3, 0.2, 0.6, 0.4, 0, 0.2, 0, -0.3, -0.2, 0, -0.6, 0, 0.3]
array= np.array(list_of_values)我需要一个相同大小的数组,当值从负数变为正数时有1,当值由正变为负数时有-1,其余数组有0。如果list_of_values中存在0,并且它反弹回来,则不应将其视为已越过0线。
这正是我正在寻找的输出
output = [0, 0, 0, 0, 1, 0, 0, 0, -1, 1, 0, 0, 0, 0, 0, -1, 0, 0, 0, 0, 1]真实的list_of_values很大,有3000+数字,所以解决方案应该使用Numpy (有些for循环是无效的),而且应该很快。
谢谢
发布于 2021-06-06 20:41:41
您可以使用numpy.ediff1d
>>> import numpy as np
>>> arr = np.array([-1, -0.8, -0.6, -0.1, 0.1, 0.5, 0.7, 1, -0.3, 0.2, 0.6])
>>> np.ediff1d(np.sign(arr), to_begin=0) // 2
array([ 0., 0., 0., 0., 1., 0., 0., 0., -1., 1., 0.])如果你认为0是积极的:
>>> arr = np.array([-1, -0.8, -0.6, -0.1, 0.0, 0.5, 0.7, 1, -0.3, 0.2, 0.6])
>>> np.ediff1d(np.where(arr==0, 1, np.sign(arr)), to_begin=0)//2
array([ 0., 0., 0., 0., 1., 0., 0., 0., -1., 1., 0.])编辑
根据您的编辑,您可以执行以下操作:
>>> arr = [-0.5, -0.8, -0.6, -0.2, 0.2, 0.5, 0.7, 0.9, -0.3, 0.2, 0.6, 0.4, 0, 0.2, 0, -0.3, -0.2, 0, -0.6, 0, 0.3]
>>> output = np.array(arr)
>>> nonzero_idx = output != 0
>>> nonzero_arr = output[nonzero_idx]
>>> res = np.ediff1d(np.sign(nonzero_arr), to_begin=0) // 2
>>> output[nonzero_idx] = res
>>> output
array([ 0., 0., 0., 0., 1., 0., 0., 0., -1., 1., 0., 0., 0.,
0., 0., -1., 0., 0., 0., 0., 1.])发布于 2021-06-06 20:55:50
Cyttorak提供的答案是正确的,而且比我的要漂亮得多,但是,如果你不介意稍微丑陋一点的代码,并想要速度,这会更快。
a2 = np.array([-1, 1])
array = np.array([-1, -0.8, -0.6, -0.1, 0.1, 0.5, 0.7, 1, -0.3, 0.2, 0.6])
array = np.where(array >= 0, -1, 1)
output = np.convolve(array, a2, mode='same')
output = np.where((output == 2) | (output == -2), output, 0) // 2编辑:对不起,忘记复制粘贴a2 :D
https://stackoverflow.com/questions/67859193
复制相似问题