简体   繁体   中英

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?

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

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)
mat[mat.sum(axis=1).astype(np.bool).flat] = 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM