user11658272
user11658272

Reputation:

python numpy matrix row wise operations: columns in each row

How can I loop over a matrix and get the number of columns in each row? If I have a matrix, and some elements are NaN (empty) in the matrix, e.g.: [[4,2,9,4],[3,4,8,6],[5,NaN,7,7],[Nan,8,Nan,Nan]], how can I compute the row-wise length?

I have tried:

len(matrix) # number of rows
=len(matrix[0]) # number of columns

But that gives me the total number.

So I want to get a vector saying the number of columns in each row: [4,4,3,1] e.g.

My idea is to make a loop like this:

for i in matrix:

And then a loop where it searches. But I'm not sure how to do this

EDIT: I tried @wavy's method and it worked. Can I do like this:

# empty list
Final=[]

for i in range(matrix):
    columns=np.isnan(matrix).sum(axis=1)
    result=-columns+matrix.shape[1]
    if result==1:
        Final.append(matrix[i])
        
        
    print(Final)

I also need to put other conditions, when result==2, and when result>2

Upvotes: 1

Views: 409

Answers (2)

Wavy
Wavy

Reputation: 188

This might be faster than David Wierichs suggestion:

import numpy as np 

x = np.array([[4, 2, 9, 4], [3, 4, 8, 6], [5, np.nan, 7, 7], [np.nan, 8, np.nan, np.nan]])
y = np.isnan(x).sum(axis=1)
result = -y + x.shape[1]

Upvotes: 1

David Wierichs
David Wierichs

Reputation: 545

You could loop over the rows and for each row use the (negated) numpy.isnan method:

lengths = [np.sum(~np.isnan(row)) for row in matrix]

As this builds up a boolean array in the np.isnan, there might be faster approaches.

Upvotes: 0

Related Questions