user1299784 user1299784 - 1 year ago 248
Python Question

Numpy: slice matrix to remove one row and column

Given an n by n matrix (technically an np.array) L, I wish to remove the kth row and kth column. This line of code works as expected (it selects the 1st through 3rd rows and columns):

Lt = L[(1,2,3),(1,2,3)]

When I try to replace (1,2,3) by a dynamically generated tuple excluding the k, it fails:

keep = (i for i in range(n) if i != k)
Lt = L[keep,keep]
# IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices

How can I do this properly?

Answer Source
keep = (i for i in range(n) if i != k)

This is a generator expression, not a generated tuple itself; instead, try

keep = tuple(i for i in range(n) if i != k)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download