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

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

大型數組的numpy矢量化操作

大型數組的numpy矢量化操作

慕村225694 2023-06-06 10:30:08
我正在嘗試通過 python3 對 numpy 數組進行一些計算。數組:? ?c0 c1 c2 c3r0 1? 5? 2? 7r1 3? 9? 4? 6r2 8? 2? 1? 3這里的“cx”和“rx”是列名和行名。如果元素不在給定的列列表中,我需要逐行計算每個元素的差異。例如?given a column list? [0, 2, 1] # they are column indices?which means that?? ? for r0, we need to calculate the difference between the c0 and all other columns, so we have?? ? [1, 5-1, 2-1, 7-1]? ? for r1,? we need to calculate the difference between the c2 and all other columns, so we have?? ? [3-4, 9-4, 4, 6-4]? ? for r2,? we need to calculate the difference between the c1 and all other columns, so we have?? ? [8-2, 2, 1-2, 3-2]所以,結果應該是? ?1 4 1 6? ?-1 5 4 2? ?6 2 -1 1因為數組可能非常大,所以我想通過 numpy 向量化操作(例如廣播)進行計算。但是,我不確定如何有效地做到這一點。我已經檢查了對 numpy 數組的矢量化操作、對 Numpy 切片操作進行矢量化、對大型 NumPy 乘法進行矢量化、用 Numpy 向量化操作替換 For 循環、對循環對 numpy 數組進行矢量化。但是,它們都不適合我。謝謝你的幫助 !
查看完整描述

1 回答

?
喵喵時光機

TA貢獻1846條經驗 獲得超7個贊

先從數組中提取值,然后做減法:


import numpy as np


a = np.array([[1,  5,  2,  7],

[3,  9,  4,  6],

[8,  2,  1,  3]])


cols = [0,2,1]


# create the index for advanced indexing

idx = np.arange(len(a)), cols


# extract values 

vals = a[idx]


# subtract array by the values

a -= vals[:, None]


# add original values back to corresponding position

a[idx] += vals 


print(a)


#[[ 1  4  1  6]

# [-1  5  4  2]

# [ 6  2 -1  1]]

操場


查看完整回答
反對 回復 2023-06-06
  • 1 回答
  • 0 關注
  • 120 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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