如何利用 Numpy 對年度前 3 名的二氧化碳資料進行排名?下圖顯示了我到目前為止所獲得的內容,我可以將它們壓縮在一起,但我不太確定如何在不弄亂索引的情況下排序和列印前 3 個。
https://i.stack.imgur.com/RIsQq.png
uj5u.com熱心網友回復:
使用 python 的標準庫:heapq.nlargest
from heapq import nlargest
c = [2013, 2014, 2015, 2016, 2017, 2018]
x = [10., 9.57, 9.27, 9.32, 9.72, 9.65]
for v,y in nlargest(3, zip(x,c)):
print('Year: {}; CO2: {}'.format(y,v))
# Year: 2013; CO2: 10.0
# Year: 2017; CO2: 9.72
# Year: 2018; CO2: 9.65
使用 numpy:numpy.argpartition
import numpy as np
cx = np.array([[2013, 2014, 2015, 2016, 2017, 2018],
[10., 9.57, 9.27, 9.32, 9.72, 9.65]])
idx_top3 = np.argpartition(cx, (-3,-2,-1))
cx_top3 = cx[:, idx_top3[1,-3:]]
print(cx_top3)
# [[2018. 2017. 2013. ]
# [ 9.65 9.72 10. ]]
也可以看看:pandas.DataFrame.nlargest
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/430968.html
