Reputation: 121
mat=[[0,1,5],[1,3,6],[-1,4,4],[1,2,2],[7,3,7],[2,5,3]]
mat matrix shape could be a 10000*5. here just an example
Here I define a function. It tries to find mat[:,0] < be or mat[:,0] > ba or mat[:,1] < bb. If one column match the condition, the element[i,0] < be the element[i,0]=be, then copy the column to another matrix "swape". Also delete this column from matrix "mat". Same as mat[:,0] > ba or mat[:,1] < bb. For mat[:,1] < bb, the colume will copy to "swapt",mat[:,0] > ba don't copy, just delete.
example be=0, ba=6,bb=3
The return list should be :
mat=[[1,3,6],[2,5,3]]
swape=[[-1,4,4]]
swapt=[[1,2,2],[0,1,5]]
The function will return mat, swape, and swapt
def swapco(be,ba,bb,mat):
swape=np.array()
swapt=np.array()
leng=np.shape(mat)[0]
for i in range(leng):
if mat[i,2]<bb:
mat[i,2]=bb
np.append(swapt,i,1)
np.delete(mat, i, 0)
else:
if mat[i,0]>=ba:
mat[i,0]=ba
np.append(swape,i,1)
np.delete(mat, i, 0)
elif mat[i,0]<=be:
mat[i,0]=be
np.append(swape,i,1)
np.delete(mat, i, 0)
i+=1
return swape, swapt
In my code, I found the matrix mat length always reduce once some columns matched the condition. It will append and delete wrong column. Also the append is append a address or a deepcopy?
If using
for col in mat:
Then how to delete itself in mat? Or any efficiency way to write this code?
Question updated...
Upvotes: 3
Views: 4213
Reputation: 25823
It's really unclear from your code what you're trying to do, but let me write a little example for you that might help you get started cleaning up your code.
import numpy as np
def split(mat, a, b):
assert a < b
where_less_than_a = mat[:, 0] < a
where_less_than_b = mat[:, 0] < b
less_than_a = mat[where_less_than_a, :]
between_a_b = mat[(~where_less_than_a) & where_less_than_b, :]
greater_eq_b = mat[(~where_less_than_b), :]
return less_than_a, between_a_b, greater_eq_b
mat = np.arange(27).reshape((9, 3))
x, y, z = split(mat, 4., 17.)
print(x)
# [[0 1 2]
# [3 4 5]]
print(y)
# [[ 6 7 8]
# [ 9 10 11]
# [12 13 14]
# [15 16 17]]
print(z)
# [[18 19 20]
# [21 22 23]
# [24 25 26]]
I hope the above example helps you get started on your own project. There is one thing that might be a little confusing, the ~
in the code above is used as a "logical not" operator. It can be used in this way with numpy arrays of type bool
, but be careful because it has a different meaning for other python objects (it's called the complement operator).
Upvotes: 2