-1

I am trying to somewhat elegantly sort a 2 by 2 Numpy array so that the letters keep being grouped up with their respected start float values. But the float values should be sorted from highest to lowest.

this = {"z": 1.6, "aaaaaaaaaaaaa": 0, "w": 6, "v": 4}
orThis = [['z' '1.6']
 ['aaaaaaaaaaaaa' '0']
 ['w' '6']
 ['v' '4']]

shouldBecomeThis = [['w', 6. ],
                 ['v', 4. ],
                 ['z', 1.6],
                 ['aaaaaaaaaaaaa', 0 ]]

the reason why the result is supposed to look exactly like this, is because i want to feed it into a pandas dataframe

import pandas as pd

def plotTable(data, header):        
  fig, ax = plt.subplots()
  fig.patch.set_visible(False)
  ax.axis('off')
  ax.axis('tight')     
  df = pd.DataFrame(data, columns=["gene", header])
  #top line throws error if i feed it data= [('w', 6. ) ('v', 4. ) ('z', 1.6) ('aaaaaaaaaaaaa', 0. )]       
  ax.table(cellText=df.values, colLabels=df.columns, loc='center')            
  fig.tight_layout()                       
  plt.show()

foo = [['w', 6. ],
      ['v', 4. ],
      ['z', 1.6],
      ['aaaaaaaaaaaaa', 0 ]]

plotTable(foo, "SomeTableHeader")
#Plots a table. 
sortData = {"z": 1.6, "aaaaaaaaaaaaa": 0, "w": 6, "v": 4}
npArray = np.array(list(sortData.items()))
sortData = np.array(list(sortData.items()), dt)
sortData.view('<U16,<f8').sort(order=['f1'], axis=0)
sortData = np.flip(sortData, 0)
print(sortData)
#best i got so far: [('w', 6. ) ('v', 4. ) ('z', 1.6) ('aaaaaaaaaaaaa', 0. )]

I already looked this one up, but it couldn't make it work: Sorting arrays in NumPy by column

  • Which of these variables is your input and which the desired output? – drops Aug 03 '20 at 17:25
  • Does this answer your question? [How do I sort a list of dictionaries by a value of the dictionary?](https://stackoverflow.com/questions/72899/how-do-i-sort-a-list-of-dictionaries-by-a-value-of-the-dictionary) – Akshay Sehgal Aug 03 '20 at 20:25

2 Answers2

2

import numpy as np
this = {"z": 1.6, "aaaaaaaaaaaaa": 0, "w": 6, "v": 4}
array=np.array([[key,val] for (key,val) in this.items()])
sortedArr = array[array[:,1].argsort()[::-1]]
print(sortedArr)
Subasri sridhar
  • 809
  • 5
  • 13
1

I think a simple sorted should help you get that output -

d = {"z": 1.6, "aaaaaaaaaaaaa": 0, "w": 6, "v": 4}
sorted(d.items(), key=lambda x:x[1], reverse=True)
[('w', 6), ('v', 4), ('z', 1.6), ('aaaaaaaaaaaaa', 0)]

You can apply a dict() on the output to get back a dictionary if you need.

Akshay Sehgal
  • 18,741
  • 3
  • 21
  • 51