我有一个包含一堆行和三列的数组。我有下面的代码将每个超过阈值的值更改为0.是否有一个技巧可以使替换值为负数,哪个数字超过阈值?假设我有一个数组np.array([[1,2,3],[4,5,6],[7,8,9]])
。我选择第一列并获得一个值为1,4,7的数组(每行的第一个值)如果阈值为5,是否有办法使每个值大于5到它的负值,因此1 ,4,7变为1,4,-7?
import numpy as np
arr = np.ndarray(my_array)
threshold = 5
column_id = 0
replace_value = 0
arr[arr[:, column_id] > threshold, column_id] = replace_value
答案 0 :(得分:2)
试试这个
In [37]: arr = np.array([[1,2,3],[4,5,6],[7,8,9]])
In [38]: arr[:, column_id] *= (arr[:, column_id] > threshold) * -2 + 1
In [39]: arr
Out[39]:
array([[ 1, 2, 3],
[ 4, 5, 6],
[-7, 8, 9]])
很抱歉以后再编辑。我建议在下面,这可能会更快。
In [48]: arr
Out[48]:
array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
In [49]: col = arr[:, column_id]
In [50]: col[col > threshold] *= -1
In [51]: arr
Out[51]:
array([[ 1, 2, 3],
[ 4, 5, 6],
[-7, 8, 9]])
答案 1 :(得分:0)
import numpy as np
x= list(np.arange(1,10))
b = []
for i in x:
if i > 4:
b.append(-i)
else:
b.append(i)
print(b)
e = np.array(b).reshape(3,3)
print('changed array')
print(e[:,0])
output :
[1, 2, 3, 4, -5, -6, -7, -8, -9]
changed array :
[ 1 4 -7]