Python: Select last value of each column that is nonzero in a matrix

Viewed 48

I'm looking for a command to pick the last element of my matrix that is nonzero. Not the index of the value, but the actual value. It's a (1001,50001) matrix where the last value of each column isn't the same.

It is not a dataframe, so preferably a numpy command.

2 Answers

You can use np.argsort on the mask a!=0:

a[(a!=0).argsort(axis=0)[-1], range(a.shape[1])]

I have a suggestion for that. Replace all non-zero values of your column with 1. Then find the last element that is equal to 1. That would be easy even using Unix using grep '1' file | tail -1 , etc. If however you are not allowed to modify the matrix values then you need to just extract this column and run the scripts for this column only. Good luck.

Related