Replace data of an array by 2 values of a second array

前端 未结 2 1678
小鲜肉
小鲜肉 2021-01-15 18:20

I have two numpy arrays \"Elements\" and \"nodes\". My aim is to gather some data of these arrays. I need to remplace \"Elements\" data of the two last columns by the two co

2条回答
  •  醉梦人生
    2021-01-15 18:34

    Instead of appending the results to some array or list, you may consider creating the resulting array before you go through the loop.

    Here is my solution for you problem using a fop loop and 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)
    

    which gives as output

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

    There may be pure numpy solutions (without the for-loop). That then might be much faster than this.

提交回复
热议问题