I get a ndarray
reading it from a file, like this
my_data = np.genfromtxt(input_file, delimiter='\t', skip_header=0)
Example input (parsed)
[[ 2. 1. 2. 0.]
[ 2. 2. 100. 0.]
[ 2. 3. 100. 0.]
[ 3. 1. 2. 0.]
[ 3. 2. 4. 0.]
[ 3. 3. 6. 0.]
[ 4. 1. 2. 0.]
[ 4. 2. 4. 0.]
[ 4. 3. 6. 0.]]
Longer example input (unparsed).
The first 2 columns are supposed to be int
, while the last 2 columns are supposed to be float
, but that's what I get. Suggestions are welcome.
The main problem is, I'm trying to sort it, using Numpy, so that rows get ordered giving precedence to the numbers on second column first, and on the first column next.
Example of desired output
[[ 2. 1. 2. 0.]
[ 3. 1. 2. 0.]
[ 4. 1. 2. 0.]
[ 2. 2. 100. 0.]
[ 3. 2. 4. 0.]
[ 4. 2. 4. 0.]
[ 2. 3. 100. 0.]
[ 3. 3. 6. 0.]
[ 4. 3. 6. 0.]]
I'm aware of this answer, it works for sorting rows on a single column.
I tried sorting on the second column, since the first one is already sorted, but it's not enough. On occasion, the first column gets reordered too, badly.
new_data = my_data[my_data[:, 1].argsort()]
print(new_data)
#output
[[ 2. 1. 2. 0.]
[ 4. 1. 2. 0.] #ouch
[ 3. 1. 2. 0.] #ouch
[ 2. 2. 100. 0.]
[ 3. 2. 4. 0.]
[ 4. 2. 4. 0.]
[ 2. 3. 100. 0.]
[ 3. 3. 6. 0.]
[ 4. 3. 6. 0.]]
I've also checked this question
The answer mentions
The problem here is that np.lexsort or np.sort do not work on arrays of dtype object. To get around that problem, you could sort the rows_list before creating order_list:
import operator
rows_list.sort(key=operator.itemgetter(0,1,2))
But I there is no key
parameter in the sort
function of type ndarray
. And merging fields is not an alternative in my case.
Also, I don't have a header, so, if I try to sort using the order
parameter, I get an error.
ValueError: Cannot specify order when the array has no fields.
I'd rather sort in place or at least obtain a result of the same type ndarray
. Then I want to save it to a file.
How do I do this, without messing the datatypes?