亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

從 2D numpy 數組中提取任意小計

從 2D numpy 數組中提取任意小計

桃花長相依 2023-10-26 10:46:09
我有二維計數數組,需要從中提取任意小計序列。在此示例中,它們是小計列。每個小計是任意基列集合的總和,由加數索引元組表示:>>> 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調用/表達式來完成此操作,而無需for循環創建各個小計列的元組?請注意,加數索引是任意的;并非所有索引都需要出現在小計中,索引不一定按升序出現,并且同一索引可以出現在多個小計中。
查看完整描述

2 回答

?
慕哥9229398

TA貢獻1877條經驗 獲得超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.concatenatenp.fromiter(itertools.chain(*subtotal_addend_idxs), dtype=int)。


查看完整回答
反對 回復 2023-10-26
?
繁星coding

TA貢獻1797條經驗 獲得超4個贊

由于我們不能使用np.take,這是我的解決方案(函數中仍然有一個 for 循環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)


查看完整回答
反對 回復 2023-10-26
  • 2 回答
  • 0 關注
  • 153 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號