簡體   English   中英

如何獲得數組的 10 個最小數字?

[英]How do I get the 10 smallest numbers of an array?

這是我的代碼:

from astropy.io import fits
import pandas
import matplotlib.pyplot as plt
import numpy as np
import heapq 

datos = fits.open('/home/citlali/Descargas/Lista.fits')
data = datos[1].data

#Linea [SIII] 9532
Mask_1 = data['flux_[SIII]9531.1_Re_fit'] / data['e_flux_[SIII]9531.1_Re_fit'] > 5
newdata1 = data[Mask_1]

H1_alpha = newdata1['log_NII_Ha_Re']

H1_beta = newdata1['log_OIII_Hb_Re']

M = H1_alpha < -0.9

newx = H1_alpha[M] #This is my array where I need the smallest 10 numbers
newy = H1_beta[M]  

sm = heapq.nsmallest(10, newx)

plt.plot(sm, newy, 'ro')  

我想要 10 個最小的 newx 數字,但我還需要這個數字的“y”值(newy)以及如何獲取它們。 謝謝。

heapq.nsmallest 的文檔顯示您可以給它一個密鑰:

heapq.nsmallest(n, 可迭代, key=None)

這意味着您可以將 newx 和 newy 值壓縮在一起,然后根據 newx 值選擇 nsmallest。

M = H1_alpha < -0.9

newx = H1_alpha[M]
newy = H1_beta[M]  

sm = heapq.nsmallest(10, zip(newx, newy), key= lambda x: x[0])

plt.plot([i[0] for i in sm], [i[1] for i in sm], 'ro') 

newxnewy組合成一個元組列表。 然后你可以從中得到最小的 10 個,並將它們拆分回單獨的列表中進行排序。

sm = heapq.nsmallest(10, zip(newx, newy)) # zip them to sort together
newx, newy = zip(*sm) # unzip them
plt.plot(newx, newy, 'ro')

如果您的數據是基本的 Python 數據結構,您可以按照用戶 @barmar 的指示使用zip

import heapq

newx = [10, 20, 30, 40, 50, 60, 70, 80]
newy = [11, 21, 31, 41, 51, 61, 71, 81]

sm = heapq.nsmallest(4, zip(newx, newy))
print(sm)

如果您使用的是pandas ,您可以使用該系列的.nsmallest()方法並使用結果的索引從其他系列中獲取匹配結果(為您節省創建具有再次所有數據):

from pandas import Series

newx = Series(newx)
newy = Series(newy)

smx = newx.nsmallest(4)
smy = newy[smx.index]
print(smx, smy)

如果您只是使用numpy ,則此方法有效:

import numpy as np

anewx = np.array(newx)
anewy = np.array(newy)

smxi = np.argpartition(anewx, 4)[:4]
print(anewx[smxi])
print(anewy[smxi])

組合代碼運行結果:

[(10, 11), (20, 21), (30, 31), (40, 41)]
0    10
1    20
2    30
3    40
dtype: int64 0    11
1    21
2    31
3    41
dtype: int64
[20 10 30 40]
[21 11 31 41]
def get(i, lis):
    lis.sort()
    log = []
    for op in range(i):
        log.append(op)
    return log

mylist = [5, 6, 8, 9, 1, 14, 52, 10, 65, 12, 65]
print(get(10, mylist))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM