Merge two numpy arrays

77,946

Solution 1

Use np.array and then np.concatenate,

import numpy as np

first = np.array([[650001.88, 300442.2,   18.73,  0.575,  
                   650002.094, 300441.668, 18.775],
                  [650001.96, 300443.4,   18.7,   0.65,   
                   650002.571, 300443.182, 18.745],
                  [650002.95, 300442.54,  18.82,  0.473,  
                   650003.056, 300442.085, 18.745]])

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

np.concatenate((first, second), axis=1)

Where axis=1 means that we want to concatenate horizontally.

That works for me

Solution 2

Use np.column_stack:

import numpy as np

first = [[650001.88, 300442.2,   18.73,  0.575,  650002.094, 300441.668, 18.775],
         [650001.96, 300443.4,   18.7,   0.65,   650002.571, 300443.182, 18.745],
         [650002.95, 300442.54,  18.82,  0.473,  650003.056, 300442.085, 18.745]]

second = [[1],
          [2],
          [3]]

np.column_stack([first, second])

If you need it as a list, use the method tolist:

np.column_stack([first, second]).tolist()
Share:
77,946

Related videos on Youtube

Losbaltica
Author by

Losbaltica

Updated on February 13, 2022

Comments

  • Losbaltica
    Losbaltica over 2 years

    I am trying to merge two arrays with the same number of arguments.

    Input:

    first = [[650001.88, 300442.2,   18.73,  0.575,  650002.094, 300441.668, 18.775],
             [650001.96, 300443.4,   18.7,   0.65,   650002.571, 300443.182, 18.745],
             [650002.95, 300442.54,  18.82,  0.473,  650003.056, 300442.085, 18.745]]
    
    second = [[1],
              [2],
              [3]]
    

    My expected output:

    final = [[650001.88, 300442.2,   18.73,  0.575,  650002.094, 300441.668, 18.775, 1],
             [650001.96, 300443.4,   18.7,   0.65,   650002.571, 300443.182, 18.745, 2],
             [650002.95, 300442.54,  18.82,  0.473,  650003.056, 300442.085, 18.745, 3]]
    

    To do that I create simple loop:

    for i in first:
            for j in second:
                final += np.append(j, i)
    

    I got i filling that i missing something. First of all my loop i extremely slow. Secondly my data is quite have i got more than 2 mlns rows to loop. So I tried to find faster way for example with this code:

    final = [np.append(i, second[0]) for i in first] 
    

    It working far more faster than previous loop but its appending only first value of second array. Can you help me?