3 回答

TA貢獻(xiàn)1830條經(jīng)驗(yàn) 獲得超9個(gè)贊
您可以將其轉(zhuǎn)化為一維問(wèn)題
def convert_inds(a,b,array_shape):
nrows,ncols = array_shape
to_take = np.zeros(sum(b))
count = 0
for ind,item in enumerate(b):
start_ind = ind*ncols+a[ind]
to_take[count:count+item] = np.arange(start_ind,start_ind+item)
count += item
return to_take.astype(np.int)
to_take = convert_inds(a,b,c.shape)
c.ravel()[to_take] = 1
在上面的代碼中,convert_inds將a和轉(zhuǎn)換b為
array([ 2, 3, 13, 14, 15, 21, 22, 23, 24, 25, 26, 27, 34])
它們是1展平后 s的索引c。通過(guò)這樣做,您只需要b在函數(shù)中進(jìn)行迭代即可convert_inds。

TA貢獻(xiàn)1936條經(jīng)驗(yàn) 獲得超7個(gè)贊
我實(shí)現(xiàn)了下一個(gè)解決方案,沒(méi)有任何 Python 循環(huán),只有純 NumPy 代碼。也許它不像 python-loop 解決方案那么簡(jiǎn)單,但肯定會(huì)快得多,特別是對(duì)于大數(shù)據(jù)。
import numpy as np
def set_val_2d(a, val, starts, lens):
begs = starts + np.arange(a.shape[0]) * a.shape[1]
ends = begs + lens
clens = lens.cumsum()
ix = np.ones((clens[-1],), dtype = np.int64)
ix[0] = begs[0]
ix[clens[:-1]] = begs[1:] - ends[:-1] + 1
ix = ix.cumsum()
a.ravel()[ix] = val
a = np.array([2,3,1,4])
b = np.array([2,3,7,1])
c = np.zeros((4, 10))
set_val_2d(c, 1, a, b)
print(c)
輸出:
[[0. 0. 1. 1. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 1. 1. 1. 0. 0. 0. 0.]
[0. 1. 1. 1. 1. 1. 1. 1. 0. 0.]
[0. 0. 0. 0. 1. 0. 0. 0. 0. 0.]]

TA貢獻(xiàn)1719條經(jīng)驗(yàn) 獲得超6個(gè)贊
如果您選擇基于索引的奇特方法,最困難的部分是查找軸 1 的索引。這非常類似于:
>>> np.repeat(a, b)
array([2, 2, 3, 3, 3, 1, 1, 1, 1, 1, 1, 1, 4])
除了每組索引應(yīng)該遞增之外。可以使用以下函數(shù)完成此修復(fù):
def accumulative_count(counts, initial):
counter = np.ones(np.sum(counts), dtype=int)
marker_idx = np.r_[0, np.cumsum(counts)[:-1]]
subtract_vals = np.r_[1, counts[:-1]]
initial_vals = np.r_[initial[0], np.diff(initial)]
counter[marker_idx] = counter[marker_idx] - subtract_vals + initial_vals
return np.cumsum(counter)
>>> accumulative_count(counts, initial)
array([2, 3, 3, 4, 5, 1, 2, 3, 4, 5, 6, 7, 4], dtype=int32)
畢竟,你有能力完成它:
c[np.repeat(np.arange(len(c)), b), accumulative_count(b, a)] = 1
c:
array([[0., 0., 1., 1., 0., 0., 0., 0., 0., 0.],
[0., 0., 0., 1., 1., 1., 0., 0., 0., 0.],
[0., 1., 1., 1., 1., 1., 1., 1., 0., 0.],
[0., 0., 0., 0., 1., 0., 0., 0., 0., 0.]])
添加回答
舉報(bào)