python - 将一个数组的数据替换为第二个数组的 2 个值

标签 python arrays numpy

我有两个 numpy 数组“Elements”和“nodes”。我的目标是聚集 这些数组的一些数据。 我需要用“节点”数组中包含的两个坐标替换最后两列的“元素”数据。 这两个数组非常巨大,我必须自动化它。

一个例子:

import numpy as np

Elements = np.array([[1.,11.,14.],[2.,12.,13.]])

nodes = np.array([[11.,0.,0.],[12.,1.,1.],[13.,2.,2.],[14.,3.,3.]])

results = np.array([[1., 0., 0., 3., 3.],
[2., 1., 1., 2., 2.]])

我认为使用“if”和“for循环”可以做到这一点,但我不知道如何附加结果......

test=[]
for i in range(Elements.shape[0]):
    if (Elements[:,:1] == nodes[i,0]):

最佳答案

您可以考虑在执行循环之前创建结果数组,而不是将结果附加到某个数组或列表。

这是我使用 fop 循环和 np.where 解决您的问题的解决方案。

import numpy as np
# I used numpy 1.10.1 here

Elements = np.array([[1.,11.,14.],[2.,12.,13.]])
nodes = np.array([[11.,0.,0.],[12.,1.,1.],[13.,2.,2.],[14.,3.,3.]])

# Create an array with enough rows and five columns
res = np.zeros((np.shape(Elements)[0],5))

for i in range(np.shape(Elements)[0]):
    res[i,0] = Elements[i,0] # The first column stays the same

    # Find the Value of the 2nd column of Elements in the first column of nodes.
    nodesindex = np.where(nodes[:,0]==Elements[i,1])
    # Replace second and third row of the results with the ventries from nodes.
    res[i,1:3]=nodes[nodesindex,1:3]

    #Do the same for the 3rd column of Elements
    nodesindex = np.where(nodes[:,0]==Elements[i,2])
    res[i,3:5]=nodes[nodesindex,1:3]

print(res)

作为输出给出

[[ 1.  0.  0.  3.  3.]
[ 2.  1.  1.  2.  2.]]

可能有纯 numpy 解决方案(没有 for 循环)。那么可能会比这快得多。

关于python - 将一个数组的数据替换为第二个数组的 2 个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33712943/

相关文章:

php - 如何合并两个数组并对重复键的值求和?

javascript - 如何测试数组项的文本是否包含子字符串?

python-3.x - 机器学习预处理错误

python - 如何在 Pandas DataFrame 中将 True/False 映射到 1/0?

php - php中的支付api多维数组问题

python - 在 numpy 数组中围绕定义的对角线设置递增值

python - 如何将 cloudwatch 目标输入作为参数传递给 Lambda 函数

python - Pycairo 比例失真

python - 从多处理中的异常返回值

python - smtpauthenticationerror 534 django python 注册