Mejdi Dallel
Mejdi Dallel

Reputation: 642

Fill a numpy matrix's certain column with 1 if all columns are 0

Let's say I have this matrix :

> mat
  index   values
    0   0 0 0 0 0
    1   0 0 0 0 0
    2   0 1 0 0 0
    3   0 1 0 0 0
    4   0 0 0 0 0
    5   0 0 0 0 0
    6   0 0 1 0 0
    7   0 0 1 0 0
    8   0 0 0 0 0

I want to fill mat's first column with the value 1 if all the columns in the iterated row are 0.

So that mat will look like this :

> mat
  index   values
    0   1 0 0 0 0
    1   1 0 0 0 0
    2   0 1 0 0 0
    3   0 1 0 0 0
    4   1 0 0 0 0
    5   1 0 0 0 0
    6   0 0 1 0 0
    7   0 0 1 0 0
    8   1 0 0 0 0

Here's what I have tried :

for i in range(len(mat)):
   for j in range(5):
       if (mat[i][j]!=1):
           mat[i][0]=1

But this puts 1 in all columns. Why ?

Upvotes: 1

Views: 79

Answers (3)

AGN Gazer
AGN Gazer

Reputation: 8388

mat[mat.sum(axis=1).astype(np.bool).flat] = 1

Upvotes: 0

henrywongkk
henrywongkk

Reputation: 1918

An alternative solution is to evaluate the row with numpy.any():

for i in range(len(mat)):
   mat[i][0] = 0 if np.any(mat[i]) else 1

or simply without a for-loop

mat[:,0] = ~np.any(mat, axis=1)

Upvotes: 2

Sanil Khurana
Sanil Khurana

Reputation: 1169

for i in range(len(mat)):
  for j in range(5):
      if (mat[i][j]!=1):
          mat[i][0]=1

This doesn't work because it would set the first column to 1 if any column has a zero. You want to set first column to 1 if all columns have a 0

This would work

for i in range(len(mat)):
  for j in range(5):
      if (mat[i][j]==1):
          break;
      mat[i][0] = 1

Also, a much better solution would be to use sum

for i in range(len(mat)):
  if (sum(mat[i]) == 0):
     mat[i][0] = 1

Upvotes: 2

Related Questions