-1

I have the following problem:

I have a matrix. Now, I want to delete one entry in each row of the matrix: In rows that contain a certain number (say 4) I want to delete the entry with that number, and in other rows I simply want to delete the last element.

E.g. if I have the matrix

    matrix=np.zeros((2,2))
    matrix[0,0]=2
    matrix[1,0]=4
    matrix

which gives

2 0

4 0

after the deletion it should simply be

2

0

thanks for your help!

alan
  • 48
  • 1
  • 13

1 Answers1

1

so, assuming there's maximum only one 4 in a row, what you want to do is:

  1. iterate all rows, and if there's a four use roll so it becomes the last element
  2. delete the last column

in rows that have 4, it will delete this 4 and shift the remaining values that come after it, in rows that don't have 4, it will delete the last element.

(I took the liberty of trying with a little bigger matrix just to make sure output is as expected)

try this:

import numpy as np


# Actual solution
def remove_in_rows(mat, num):
    for i, row in enumerate(mat):
        if num in row.tolist():
            index = row.tolist().index(num)
            mat[i][index:] = np.roll(row[index:], -1)
    return np.delete(mat, -1, 1)


# Just some example to demonstrate it works
matrix = np.array([[10 * y + x for x in range(6)] for y in range(6)])
matrix[1, 2] = 4
matrix[3, 3] = 4
matrix[4, 0] = 4

print("BEFORE:")
print(matrix)

matrix = remove_in_rows(matrix, 4)

print("AFTER:")
print(matrix)

Output:

BEFORE:
[[ 0  1  2  3  4  5]
 [10 11  4 13 14 15]
 [20 21 22 23 24 25]
 [30 31 32  4 34 35]
 [ 4 41 42 43 44 45]
 [50 51 52 53 54 55]]
AFTER:
[[ 0  1  2  3  5]
 [10 11 13 14 15]
 [20 21 22 23 24]
 [30 31 32 34 35]
 [41 42 43 44 45]
 [50 51 52 53 54]]
Adam.Er8
  • 12,675
  • 3
  • 26
  • 38
  • 1
    If you now pack the actual code in a function, like `remove_in_rows(num)`, you can ship it. – Finomnis Jun 27 '19 at 13:23
  • If you give a full working example that also constructs example arguments, it is just too confusing to put it all in one big code blob – Finomnis Jun 27 '19 at 13:41
  • agreed, defining a function really helps see what is the "solution code" and what is just there for the example. – Adam.Er8 Jun 27 '19 at 13:47
  • 1
    Also, you can create the matrix like that: `matrix = np.array([[10*y+x for x in range(6)] for y in range(6)])`. That would also get rid of the problem that your values are floats. – Finomnis Jun 27 '19 at 13:48
  • oh nice! I tried doing it with `np.ndarray` and got an error, that's why I went for the loop, oopsy: https://stackoverflow.com/questions/15879315/what-is-the-difference-between-ndarray-and-array-in-numpy – Adam.Er8 Jun 27 '19 at 13:50
  • Also, I think the roll is slow and unnecessary. Here is my solution. I didn't just want to add a second answer, because I like your example code. If you want to adapt it, feel free to just copy paste it. If not, also fine. https://pastebin.com/ef8HCSxS – Finomnis Jun 27 '19 at 14:16