我有二維計數(shù)數(shù)組,需要從中提取任意小計序列。在此示例中,它們是小計列。每個小計是任意基列集合的總和,由加數(shù)索引元組表示:>>> A[[11, 12, 13, 14, 15] [21, 22, 23, 24, 25] [31, 32, 33, 34, 35]]>>> subtotal_addend_idxs((0, 1), (1, 2, 3), (3, 4))>>> desired_result[[23, 39, 29] [43, 69, 49] [63, 99, 69]]到目前為止我擁有的最好的代碼是這樣的:subtotal_addend_idxs = ((0, 1), (1, 2, 3), (3, 4))np.hstack( tuple( np.sum(A[:, subtotal_addend_idxs], axis=1, keepdims=True) for addend_idxs in self._column_addend_idxs ))有沒有一種聰明的方法可以通過單個numpy調(diào)用/表達式來完成此操作,而無需for循環(huán)創(chuàng)建各個小計列的元組?請注意,加數(shù)索引是任意的;并非所有索引都需要出現(xiàn)在小計中,索引不一定按升序出現(xiàn),并且同一索引可以出現(xiàn)在多個小計中。
2 回答

慕哥9229398
TA貢獻1877條經(jīng)驗 獲得超6個贊
嘗試np.add.reduceat
:
lens?=?[len(n)?for?n?in?subtotal_addend_idxs] c?=?np.concatenate(subtotal_addend_idxs) output?=?np.add.reduceat(A[:,c],?np.cumsum([0]+lens)[:-1],?axis=1)
輸出:
array([[23,?39,?29], ???????[43,?69,?49], ???????[63,?99,?69]],?dtype=int32)
備注:更快的選項np.concatenate
是np.fromiter(itertools.chain(*subtotal_addend_idxs), dtype=int)
。

繁星coding
TA貢獻1797條經(jīng)驗 獲得超4個贊
由于我們不能使用np.take,這是我的解決方案(函數(shù)中仍然有一個 for 循環(huán)lambda...)
test = np.array([[11, 12, 13, 14, 15],
[21, 22, 23, 24, 25],
[31, 32, 33, 34, 35]])
inds = ((0, 1), (1, 2, 3), (3, 4))
fake_take = lambda array,inds:[np.sum(array[list(ind)]) for ind in inds]
np.apply_along_axis(lambda x:fake_take(x,inds),1,test)
添加回答
舉報
0/150
提交
取消