[英]Python: Returning values of matrix that are in a specific range, range is given as a tuple(from, to)
School problem:学校问题:
Define a 2 parameter (inputs) function that will return the average value for elements that are within a given range.定义一个 2 参数(输入)function,它将返回给定范围内元素的平均值。 Range is given as a tuple.
范围以元组形式给出。
I must compose 2 functions:我必须编写 2 个函数:
1 is using loops; 1是使用循环;
2 is using operations.二是使用操作。
def mygmean(array,tuple): # Determines values inside and outside a specified range
"""
Determines values inside and outside a specified range.
"""
import numpy as np
incluided = []
excluded = []
for k in range(0, array.shape[0]):
for i in range(0, array.shape[1]):
if array[k,i] < tuple[0] or array[k,i] > tuple[-1]:
excluded.append(array[k,i])
pass
else:
incluided.append(array[k,i])
final_geomean = np.prod(incluided)**(1/len(incluided))
print(array)
print(incluided)
print(excluded)
print(final_geomean)
return(final_geomean,excluded)
Edit: Solved Part #1 by writing:编辑:通过编写解决了第 1 部分:
def mygmean(array,t): # Determines values inside and outside a specified range
"""
Determines values inside and outside a specified range.
"""
import numpy as np
incluided = []
excluded = []
for k in range(0, array.shape[0]):
for i in range(0, array.shape[1]):
if array[k,i] < t[0] or array[k,i] > t[-1]:
excluded.append(array[k,i])
pass
else:
incluided.append(array[k,i])
final_geomean = np.prod(incluided)**(1/len(incluided))
return(final_geomean,excluded)
Console input:控制台输入:
mygmean(np.array([[2,4],[-9,3],[6,-2],[8,1],[12,8]]),(0,10)))
Desired output:所需的 output:
(3.684369762785971, array([-9, -2, 12]))
A vectorized (ie non-loop) version would be to use nympy.where
and numpy.nanmean
:矢量化(即非循环)版本将使用
nympy.where
和numpy.nanmean
:
import numpy as np
def mygmean(array, t):
return np.nanmean(np.where((array>=t[0]) & (array<t[1]), array, np.nan))
# example
a = np.array([[1,2,3], [4,5,6]])
mygmean(a, (2,5))
# 3.0
NB.注意。 I assumed here included lower bound and excluded upper bound
我假设这里包括下限和排除上限
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.