frazman
frazman

Reputation: 33293

Filling empty list with zero vector using numpy

So here is the thing. I have a list of lists and some of the list are empty... but if it is not empty.. all the list are of fix length.. the length which I dont know.. For example

  for feature in features:
     print len(feature)

This will print either 0 or length k.

I am trying to write a function

  def generate_matrix(features):
     # return matrix

Which returns a numpy matrix.. with empty rows replaces with zero vector. Is there a way to do this efficiently? I mean... I don't want to loop thru to find the shape of matrix and then again loop thru to generate row (with either np.array(feature) or np.zeros(shape)..

Upvotes: 0

Views: 1101

Answers (1)

derricw
derricw

Reputation: 7036

Edit: I didn't realize that all of the non-empty features were the same length. If that is the case then you can just use the length of the first non-zero one. I added a function that does that.

f0 = [0,1,2]
f1 = []
f2 = [4,5,6]

features = [f0, f1, f2]

def get_nonempty_len(features):
    """
    returns the length of the first non-empty element
        of features.     
    """
    for f in features:
        if len(f) > 0:
            return len(f)
    return 0

def generate_matrix(features):
    rows = len(features)
    cols = get_nonempty_len(features)
    m = np.zeros((rows, cols))
    for i, f in enumerate(features):
        m[i,:len(f)]=f
    return m

print(generate_matrix(features))

Output looks like:

[[ 0.  1.  2.]
 [ 0.  0.  0.]
 [ 4.  5.  6.]]

Upvotes: 2

Related Questions