Declaring 2D numpy array with unknown size

14,068

If you don't know the size before-hand, then don't use a numpy array to accumulate the values. Use a flexible container (e.g. a list) and then convert to a numpy array afterwards.

If you're working with something really large, there's also numpy.fromiter which will behave quite a bit more efficiently, but you'll have to jump through a couple of hoops to use it with >1D arrays.

As an example of the first suggestion, let's say we're creating an array that will always have 10 columns, but we have no way of knowing how many rows there are. We'll use a list to store each row, and then convert to a 2D array at the end:

import numpy as np

data = []

random_val = 1
while random_val > 0.05:
    data.append(np.arange(10))
    random_val = np.random.random()

data = np.array(data)
print data.shape
Share:
14,068
m_amber
Author by

m_amber

SOreadytohelp

Updated on June 04, 2022

Comments

  • m_amber
    m_amber almost 2 years

    I m new to numpy. I m trying to define a 2-d numpy array to read images, the size of which varies.So, i cant predefine the size of the array. My code is

    np.ndarray(np.float64) I
    for i in range(len(filename)):
        I=imread(filename)     //reading an image here
        I1=I.resize(256,256)   //resizing the image
    

    Please suggest the corrections to the code.

    Thank you in advance.

  • Saullo G. P. Castro
    Saullo G. P. Castro over 10 years
    I'm wondering why the downvote...