[英]How do I remove two smallest numbers from a numpy array and calculate median python 3
I am generating a 5x3 random array.我正在生成一个 5x3 随机数组。 I need to identify and remove the smallest two numbers and then calculate the median with rest of the numbers.我需要识别并删除最小的两个数字,然后用数字的 rest 计算中位数。 I am able to identify the smallest number, but unable to proceed further.我能够识别最小的数字,但无法继续进行。
import numpy as Np
a = Np.random.randint(100, size = (5,3))
print(a)
print('\n')
sort1 = Np.concatenate(a, axis=0)
print("Concatenated: ", sort1)
print('\n')
sort2 = Np.sort(sort1)
print(sort2)
print('\n')
c = Np.min(sort2,0) #min
print(c)
print('\n')
med = Np.median(sort2)
print("Median is: ", med)
You can do it like this:你可以这样做:
a = Np.random.randint(100, size = (5,3))
a = Np.delete(a, a.argmin())
a = Np.delete(a, a.argmin())
Np.median(a)
# 48.0
Well, you managed to get the smallest number, now you need to remove it.好吧,您设法获得了最小的数字,现在您需要将其删除。
I would create a list, you don't actually need an array to calculate the median.我会创建一个列表,您实际上并不需要一个数组来计算中位数。 After creating the list it gets easier, you remove the items with list.remove() and the median function stays the same.创建列表后变得更容易,您使用 list.remove() 删除项目,中位数 function 保持不变。
Your code will look like this:您的代码将如下所示:
import numpy as Np
a = Np.random.randint(100, size = (5,3))
sort1 = list(Np.concatenate(a, axis=0))
sort1.remove(min(sort1))
med = Np.median(sort1)
sort1.remove(min(sort1))
med2 = Np.median(sort1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.