給定一個二維陣列,我可以將行切片設定為特定值
import numpy as np
a = np.zeros(25).reshape(5,-1).astype(int)
a[0][2:4] = 1.0
a
array([[0, 0, 1, 1, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0]])
我正在嘗試將多個行切片設定為特定值,每行都有一個唯一切片。
我有兩個陣列中切片的開始和結束索引
starts = np.array([2, 0, 1, 3, 2])
ends = np.array([5, 3, 4, 5, 4])
但我似乎無法找到將二維陣列的這些切片設定為特定值的方法
a[starts:ends] = 1
結果是TypeError: only integer scalar arrays can be converted to a scalar index
uj5u.com熱心網友回復:
如果目標陣列的最后一維很大,那么使用基本的 Python 回圈相對高效,因為與填充陣列相比,python 回圈的開銷會很小。否則,AFAIK Numpy 不提供任何有效地執行此操作的方法(主要是因為切片的可變大小)。這是帶有 Python 回圈的基本代碼:
for i, start, end in zip(range(starts.size), starts.tolist(), ends.tolist()):
a[i, start:end] = 1
如果您想要更快的代碼,那么您可以使用 Numba 來加快回圈速度。請注意,在這種情況下您不需要呼叫tolist(其目的是通過不使用 Numpy 整數型別而是使用 CPython 整數來使代碼更快)。
uj5u.com熱心網友回復:
Numpy 有一個函式,允許您使用函式單獨沿特定軸將操作應用于陣列。因此,就我而言,我可以將操作唯一地應用于每一行。
apply_along_axis 不允許將引數傳遞給函式,除了陣列本身,所以我首先將開始和結束索引連接到我的 zeros 陣列,然后將它們從結果中分割出來。
import numpy as np
a = np.zeros(25).reshape(5,-1).astype(int)
starts = np.array([2, 0, 1, 3, 2])
ends = np.array([5, 3, 4, 5, 4])
startsT = np.expand_dims(starts, axis=0).transpose()
endsT = np.expand_dims(ends, axis=0).transpose()
aa = np.concatenate((a, startsT, endsT), axis=1)
def set_1s_by_slice(x):
x[x[-2]:x[-1]] = 1
return x
pen = np.apply_along_axis(set_1s_by_slice, 1, aa)
ult = pen[:,0:5]
ult
array([[0, 0, 1, 1, 1],
[1, 1, 1, 0, 0],
[0, 1, 1, 1, 0],
[0, 0, 0, 1, 1],
[0, 0, 1, 1, 0]])
從查看源代碼來看,這可能不會比遍歷行更快
https://github.com/numpy/numpy/blob/v1.22.0/numpy/lib/shape_base.py#L267-L414
似乎有轉換為串列,但我不確定。
uj5u.com熱心網友回復:
這似乎比使用其他答案的計算效率更高apply_along_axis
indices = np.arange(a.shape[1])
mask = (indices >= starts[:, np.newaxis]) & (indices < ends[:, np.newaxis])
a[mask] = 1
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/436825.html
上一篇:將每個物件的陣列設定為x索引元素
下一篇:遞回回圈陣列以創建物件
