gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 23:04:27 24 4
gpt4 key购买 nike

我有两个 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com