這是我的代碼:
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)以及如何獲取它們。謝謝。
uj5u.com熱心網友回復:
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')
uj5u.com熱心網友回復:
newx將和組合newy成一個元組串列。然后你可以從中得到最小的 10 個,并將它們拆分回單獨的串列中進行排序。
sm = heapq.nsmallest(10, zip(newx, newy)) # zip them to sort together
newx, newy = zip(*sm) # unzip them
plt.plot(newx, newy, 'ro')
uj5u.com熱心網友回復:
如果您的資料是基本的 Python 資料結構,您可以zip按照用戶@barmar 指示使用。
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()系列的方法并使用結果的索引從其他系列中獲取匹配結果(為您節省再次創建具有所有資料副本的第 3 個資料結構) :
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]
uj5u.com熱心網友回復:
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))
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/484859.html
上一篇:查找一維子陣列是否在二維陣列中
