如果匹配,我正在嘗試更改 np 陣列中的值
例如,一個 np 陣列a及其形狀是(50,4)
a.shape#(50,4)
我需要檢查 np 陣列在第一個軸上a是否有這個值[0,1,20,4],然后我需要將其更改為[-1,-1,-1,-1].
我試過這種格式 -
a[a==[0,1,20,4]]=[-1,-1,-1,-1]
但是,這不起作用,
如何進行此修改?
uj5u.com熱心網友回復:
np.tile也許嘗試像這樣進行逐行比較np.argwhere:
import numpy as np
# Create dummy data
x = np.random.randint(29, size=(49, 4))
x = np.concatenate([[[0,1,20,4]], x])
print('Before --> \n', x)
# Compare row-wise
x[np.argwhere(np.all(x==np.reshape(np.tile([0,1,20,4], reps=x.shape[0]), x.shape),axis=1))] = [-1,-1,-1,-1]
print('After --> \n', x)
Before -->
[[ 0 1 20 4]
[ 1 17 5 2]
[19 8 24 17]
[ 1 23 16 3]
[ 0 15 0 20]
[14 23 9 23]
[ 1 27 5 27]
[15 24 24 17]
[ 2 28 8 4]
[26 26 6 10]
[18 13 5 28]
[10 25 18 15]
[ 6 17 8 2]
[ 4 26 26 15]
[18 16 18 24]
[ 0 11 15 22]
[20 27 0 0]
[ 9 22 16 2]
[22 11 8 23]
[21 10 6 23]
[14 16 0 10]
[14 27 22 9]
[ 4 0 10 15]
[12 0 28 25]
[ 8 28 9 28]
[12 3 26 24]
[23 3 26 25]
[ 0 6 16 4]
[ 1 20 1 19]
[11 5 9 11]
[20 15 18 5]
[25 0 17 27]
[20 24 3 19]
[13 12 17 4]
[ 1 13 25 22]
[27 10 11 18]
[ 4 5 12 8]
[11 19 17 15]
[26 7 3 10]
[21 14 27 21]
[26 12 8 13]
[27 8 1 17]
[20 28 0 20]
[ 1 12 11 16]
[ 4 0 3 22]
[11 12 3 8]
[15 24 3 8]
[ 4 23 17 20]
[21 1 23 12]
[ 0 27 3 22]
[15 5 17 28]]
After -->
[[-1 -1 -1 -1]
[ 1 17 5 2]
[19 8 24 17]
[ 1 23 16 3]
[ 0 15 0 20]
[14 23 9 23]
[ 1 27 5 27]
[15 24 24 17]
[ 2 28 8 4]
[26 26 6 10]
[18 13 5 28]
[10 25 18 15]
[ 6 17 8 2]
[ 4 26 26 15]
[18 16 18 24]
[ 0 11 15 22]
[20 27 0 0]
[ 9 22 16 2]
[22 11 8 23]
[21 10 6 23]
[14 16 0 10]
[14 27 22 9]
[ 4 0 10 15]
[12 0 28 25]
[ 8 28 9 28]
[12 3 26 24]
[23 3 26 25]
[ 0 6 16 4]
[ 1 20 1 19]
[11 5 9 11]
[20 15 18 5]
[25 0 17 27]
[20 24 3 19]
[13 12 17 4]
[ 1 13 25 22]
[27 10 11 18]
[ 4 5 12 8]
[11 19 17 15]
[26 7 3 10]
[21 14 27 21]
[26 12 8 13]
[27 8 1 17]
[20 28 0 20]
[ 1 12 11 16]
[ 4 0 3 22]
[11 12 3 8]
[15 24 3 8]
[ 4 23 17 20]
[21 1 23 12]
[ 0 27 3 22]
[15 5 17 28]]
uj5u.com熱心網友回復:
這解決了形狀的隨機陣列(50,4)
b = np.random.randint(5,size=(50,4))
c = np.equal(b,[4,1,2,3])
ai = np.array(c.all(axis=1).nonzero())
np.put_along_axis(b,ai,[-1,-1,-1,-1],axis=0)
將 [4,1,2,3] 更改為 [0,1,20,4]
uj5u.com熱心網友回復:
例如對于隨機矩陣
x = np.random.randint(1,11,size=(10,4))
>> array([[10, 1, 7, 7],
[ 3, 1, 3, 2],
[ 8, 10, 2, 9],
[ 4, 6, 4, 4],
[ 1, 4, 3, 5],
[10, 1, 5, 4],
[ 7, 10, 8, 8],
[ 5, 10, 8, 3],
[ 6, 5, 5, 3],
[ 7, 2, 5, 7]])
檢查所有等于目標行的行
rows_cond = np.all(x == [1,4,3,5], axis=1)
這將回傳一個布爾陣列,可用于修改所需的行
x[rows_cond,:] = [-1,-1,-1,-1]
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/424186.html
