首页 > 解决方案 > 按一列降序对 2by2 Numpy 数组进行排序

问题描述

我正在尝试对 2 x 2 Numpy 数组进行某种优雅的排序,以便字母继续与其受尊重的起始浮点值分组。但是浮点值应该从高到低排序。

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 ]]

结果应该看起来完全像这样的原因是因为我想将它输入到熊猫数据框中

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. )]

我已经查看了这个,但它无法使它工作:Sorting arrays in NumPy by column

标签: pythonnumpysorting

解决方案



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)

推荐阅读