首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >大数组的数值向量化操作

大数组的数值向量化操作
EN

Stack Overflow用户
提问于 2020-08-20 11:15:04
回答 1查看 49关注 0票数 0

我正在尝试用python3为一个数值数组做一些计算。

数组:

代码语言:javascript
复制
   c0 c1 c2 c3
r0 1  5  2  7
r1 3  9  4  6
r2 8  2  1  3

这里的"cx“和"rx”是列名和行名。

如果元素不在给定列列表中,我需要逐行计算每个元素的差异。

例如:

代码语言:javascript
复制
 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]

因此,结果应该是

代码语言:javascript
复制
   1 4 1 6
   -1 5 4 2
   6 2 -1 1

因为数组可能非常大,所以我希望通过numpy向量化操作来进行计算,例如广播。

BuT,我不确定如何有效地做到这一点。

我已经检查了Vectorizing operation on numpy arrayVectorizing a Numpy slice operationVectorize large NumPy multiplicationReplace For Loop with Numpy Vectorized OperationVectorize numpy array for loop

但是,它们都不适合我。

谢谢你的帮助!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-08-20 11:35:15

首先从数组中提取值,然后进行减法:

代码语言:javascript
复制
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]]

Playground

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63497766

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档