我有一個inputdata包含4行和5列的二維矩陣檔案(),如下所示
1 2 3 4 5
0 2 2 4 6
1 2 5 6 1
2 4 5 6 7
我想使用 numpy.where 將所有大于 2 的值設為 1(僅適用于第二列和第三列的第二行和第三行)
預期輸出為
1 2 3 4 5
0 1 1 4 6
1 1 5 6 1
2 4 5 6 7
我的腳本是
import numpy as np
data=np.loadtxt("inputdata")
values=np.where(((data>2) & (data[1:3])))
data[values]=1
但是second condition(即我只想將第一個條件numpy.where應用于一系列行)
不管用。
我希望專家可以幫助解決這個問題。謝謝。
uj5u.com熱心網友回復:
由于您要關注的區域是連續的,您可以創建一個子陣列,然后將原始陣列的那部分替換為最終的子陣列:
# Let's say your original array is called arr.
# subarray contains the 4 values that are in the 2nd and 3rd rows and columns.
subarray = arr[1:3, 1:3]
# Do your calculations on subarray and then change arr to match.
# This has the advantage of not iterating through all of arr, only the subarray.
subarray = np.where(subarray > 2, 1, subarray)
arr[1:3, 1:3] = subarray
uj5u.com熱心網友回復:
您可以使用np.ix_高級索引來獲取子陣列,然后使用相同的索引將np.where回傳的結果分配給x:
rows = (1, 2)
cols = (1, 2)
coords = np.ix_(rows, cols)
x[coords] = np.where(x[coords] == 2, 1, x[coords])
演示:
In [11]: coords = np.ix_((1,2), (1,2))
In [12]: x[coords]
Out[12]:
array([[2, 2],
[2, 5]])
In [13]: x[coords] = np.where(x[coords] == 2, 1, x[coords])
In [14]: x
Out[14]:
array([[1, 2, 3, 4, 5],
[0, 1, 1, 4, 6],
[1, 1, 5, 6, 1],
[2, 4, 5, 6, 7]])
對于連續的子陣列,您可以只使用普通切片(請參閱 AJH 的答案)。但是,您仍然可以使用np.ix_,在我看來,它更適合使用:
rows = np.arange(1, 11) # rows 1 through 10
cols = np.arange(4, 21) # columns 4 through 20
target_value = 2 # The value to replace
substitution = 1 # The value used in replacement
coords = np.ix_(rows, cols)
x[coords] = np.where(x[coords] == target_value, substitution, x[coords])
uj5u.com熱心網友回復:
np.where(a[1:3, 2:4] > 2, 1, a[1:3, 2:4])
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/463181.html
標籤:python-3.x 麻木的
