SsRr SsRr - 1 year ago 225
Python Question

Dynamic array in Python

I´m trying to delete an specific row and column from a square list "m" iteratively. At the beginning, I used the square list like a square matrix "m" and I tried using the comand "delete" from numpy as follows:

from numpy import*
import numpy as np
#deleting row and column "0"
#x is the new matrix without the row and column "0"
print x

The problem with the command "delete" it´s I´m not sure about this command can be used in a iteratively loop. Specifically, I want to known how I can delete and specific row and column taking from a "y" list:


Note: If the number "1" appears in the list "y", in the list "m" delete the respective row and column.

If number "1" appears in the list "y", delete the respective row and column in the list "m". For example, in this case the number "1" appears in the list "y" in the position "0", we need to delete the first row and the first column in the list "m". This is the desired list "m" for the first apperance of the number "1" in the list "y":

Note: The size of the list "m" changed, now is 2x2. This is my first question, how I can use a dinamyc list in Python?. How can a specify the new dimension?.

Because the number "1" appears again in the list "y", we need to delete the respective row and column in the new list "m", in this case the desired list "m" is:

I tried in a lot of ways, I obtained this tip from this forum (another way using comprehension list):

#row to delete
#column to delete
a=[j[:column]+j[column+1:] for i,j in enumerate(m) if i!=roww]
print a

Note: I don´t know how use the dynamic arrays in python, because I need some help. Some people thinks is a homework,but is a lie, I try to learn Python because is more friendly. I used to use Fortran, but with Python I hate that. Thanks.

I´m trying to incorporate an array which specify which rows and columns must be deleted. This is my original idea:

from numpy import*
import numpy as np
for i in x:
if i==1:
print mat

In this case, with this array x this is the desired matrix "mat":


Thanks again.

Answer Source

It seems to me that applying np.delete repeatedly to the same matrix does the job:

from __future__ import print_function
import numpy as np

mat = np.array([[1,2,3],[4,5,6],[7,8,9]])
print( "initial mat:\n", mat )

rmlist = [ (2,0), (1,1) ]      # a list of (row,col) to be removed
# rmlist = [ [2,0], [1,1] ]    # this also works

for (row, col) in rmlist:
    print( "removing row", row, "and column", col )
    mat = np.delete( np.delete( mat, row, 0 ), col, 1 )
    print( mat )

Result (is this not what you expect...?):

initial mat:
 [[1 2 3]
 [4 5 6]
 [7 8 9]]
removing row 2 and column 0
[[2 3]
 [5 6]]
removing row 1 and column 1
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download