按一列降序排列2by2 Numpy数组

2024-09-27 21:32:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图对一个2×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


Tags: dfdata排序npfigpltaxheader
2条回答

我认为一个简单的sorted应该可以帮助您获得输出-

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

如果需要,可以在输出上应用dict()以获取字典


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)

相关问题 更多 >

    热门问题