johnhenry - 2 years ago 131
Python Question

# Delete columns from matrix according to its index

I have a two-dimensional matrix

`matrixK`
. For example it could be something like

``````matrixK = [[0,1,2,3,4],[5,6,7,8,9],[10,11,12,13,14]]
``````

I need to delete certain columns of the matrix, and these columns need to be chosen according to a pattern that depend on their index as columns.
In other words,

``````for i in range(number_of_columns)
if (i satisfy a certain condtion):
column[i] needs to be deleted.
``````

and as a final result I need to get the same initial
`matrixK`
, deprived of the columns that satisfy the condition. What is the best pythonic way to do that?

To make an example, referring to the
`matrixK`
defined above as an example, let's consider

``````for i in range(5):
if (i%2==0):
column[i] needs to be deleted
``````

which should delete columns 2 and 4.

This can be done two different ways depending on whether you need to delete the column in-place in the original matrix or can just replace it with a new one. An example of each way is shown below.
Note that neither requires every row of the matrix to be the same length.

``````# in-place removal of column in matrix

matrixK = [[0, 1, 2, 3, 4], [5, 6, 7, 8, 9], [10, 11, 12, 13, 14]]

for row in matrixK:
for i in reversed(range(len(row))):
if i % 2 == 0:
del row[i:i+1]

print('matrixK after: {}'.format(matrixK))
``````

Or:

``````# removal of column in matrix by recreating it

matrixK = [[0, 1, 2, 3, 4], [5, 6, 7, 8, 9], [10, 11, 12, 13, 14]]

matrixK = [[row[i] for i in range(len(row)) if i % 2] for row in matrixK]

print('matrixK after: {}'.format(matrixK))
``````

Both output:

``````matrixK after: [[1, 3], [6, 8], [11, 13]]
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download