1

I want to sort the following input by 1st column:

a = np.array([(2, 1), (1, 2), (2, 3)], dtype=[('c1', int), ('c2', int)])

[[2, 1],
[1, 2],
[2, 3]]

I've tried a.sort(order='c1') followed by print(a[::-1].

Expected output (2nd column order is preserved):

[[2, 1],
[2, 3],
[1, 2]]

Actual output:

[[2, 3],
[2, 1],
[1, 2]]
gargoylebident
  • 373
  • 1
  • 2
  • 12

2 Answers2

0

You can't do it. Those dtype tuples are bound together at a deeper level than rows. They are fields, not columns. You could sort x=a['c1'] and write it back.

In [547]: a = np.array([(2, 1), (1, 2), (2, 3)], dtype=[('c1', int), ('c2', int)])
     ...: 
In [548]: a
Out[548]: array([(2, 1), (1, 2), (2, 3)], dtype=[('c1', '<i8'), ('c2', '<i8')])
In [549]: x=np.sort(a['c1'])
In [550]: x
Out[550]: array([1, 2, 2])
In [551]: a['c1']=x
In [552]: a
Out[552]: array([(1, 1), (2, 2), (2, 3)], dtype=[('c1', '<i8'), ('c2', '<i8')])
hpaulj
  • 221,503
  • 14
  • 230
  • 353
0

Pretty sure I've figured it out. Negate it:

a['c1'] = -a['c1']
a.sort(order='c1')
a['c1'] = -a['c1']
print(a)

which results in

[(2, 1) (2, 3) (1, 2)]

I won't accept this answer yet in case someone has a more optimal solution.

gargoylebident
  • 373
  • 1
  • 2
  • 12