pythonarraysnumpymatrixconcatenation

How to concatenate an empty array with Numpy.concatenate?


I need to create an array of a specific size mxn filled with empty values so that when I concatenate to that array the initial values will be overwritten with the added values.

My current code:

a = numpy.empty([2,2])  # Make empty 2x2 matrix
b = numpy.array([[1,2],[3,4]])    # Make example 2x2 matrix
myArray = numpy.concatenate((a,b))    # Combine empty and example arrays

Unfortunately, I end up making a 4x2 matrix instead of a 2x2 matrix with the values of b.

Is there anyway to make an actually empty array of a certain size so when I concatenate to it, the values of it become my added values instead of the default + added values?


Solution

  • Like Oniow said, concatenate does exactly what you saw.

    If you want 'default values' that will differ from regular scalar elements, I would suggest you to initialize your array with NaNs (as your 'default value'). If I understand your question, you want to merge matrices so that regular scalars will override your 'default value' elements.

    Anyway I suggest you to add the following:

    def get_default(size_x,size_y):
        # returns a new matrix filled with 'default values'
        tmp = np.empty([size_x,size_y])
        tmp.fill(np.nan)
        return tmp
    

    And also:

    def merge(a, b):
        l = lambda x, y: y if np.isnan(x) else x
        l = np.vectorize(l)
        return map(l, a, b)
    

    Note that if you merge 2 matrices, and both values are non 'default' then it will take the value of the left matrix.

    Using NaNs as default value, will result the expected behavior from a default value, for example all math ops will result 'default' as this value indicates that you don't really care about this index in the matrix.