[英]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')
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')
如果您的数据是基本的 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.