![](/img/trans.png)
[英]How to write a function that returns matrix with random values from a given range in Python?
[英]Python: Returning values of matrix that are in a specific range, range is given as a tuple(from, to)
学校问题:
定义一个 2 参数(输入)function,它将返回给定范围内元素的平均值。 范围以元组形式给出。
我必须编写 2 个函数:
1是使用循环;
二是使用操作。
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)
编辑:通过编写解决了第 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)
控制台输入:
mygmean(np.array([[2,4],[-9,3],[6,-2],[8,1],[12,8]]),(0,10)))
所需的 output:
(3.684369762785971, array([-9, -2, 12]))
矢量化(即非循环)版本将使用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
注意。 我假设这里包括下限和排除上限
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.