我有一個像這樣的 3d numpy 陣列(例如)
a = np.array([
[[1, -2, 3, 4],[5, 6, 7, 8]],
[[9, 10, 11, 12],[13, 14, 15, 16]]
])
我只想將以下操作應用于內部維度中索引為 1 的列中的元素。這些元素
[-2,6,10,14]適用于上面的示例。操作將是:
# variables used in the operations
v1, v2, v3 = 12, 4, 2
# the following two operations should only be applied to specified column across all the array
# 1st operation
a[a >= v1] = v1
# output
a = np.array([
[[1, -2, 3, 4],[5, 6, 7, 8]],
[[9, 10, 11, 12],[13, 12, 15, 16]]
])
# 2nd operation
f = lambda x: -2 if(x==-2) else (x-v3)/(v2-v3)
a = f(a)
# output
a = np.array([
[[1, -2, 3, 4],[5, 2, 7, 8]],
[[9, 4, 11, 12],[13, 5, 15, 16]]
])
有人能幫我嗎?我研究了幾種 NumPy 方法,但似乎無法適應我的示例。
uj5u.com熱心網友回復:
您需要將函式更改為矢量(即接受一個陣列并輸入并回傳一個陣列作為輸出),并切片以僅將其應用于所需的“列”:
f = lambda x: np.where(x==-2, -2, (x-v3)/(v2-v3))
a[...,[1]] = f(a[...,[1]])
輸出:
array([[[ 1, -2, 3, 4],
[ 5, 2, 7, 8]],
[[ 9, 4, 11, 12],
[13, 5, 15, 16]]])
uj5u.com熱心網友回復:
a = np.array([
[[1, -2, 3, 4],[5, 6, 7, 8]],
[[9, 10, 11, 12],[13, 14, 15, 16]]
])
print(a.trasnpose()[1]).reshape(1,4)
將列印:
[[-2 10 6 14]]
或者
a.transpose()[1].flatten()
將列印:
[-2 10 6 14]
比你可以對它進行操作
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/485475.html
標籤:Python 数组 麻木的 numpy-ndarray
