繁体   English   中英

如何在不使用循环的情况下将数组裁剪为最小值和最大值

[英]How to clip an array to the minimum and maximum without using loops

我仍在学习 python,我正在编写代码以将数组裁剪为最小值和最大值,但不使用任何循环。

import numpy as np
import matplotlib.pyplot as plt

def clip(array, minimum, maximum):
    return None

array = [1,2,3,4,5,6,7,8]

minimum = input ("Enter your minimum value")
maximum = input ("Enter your maximum value")

# min = minimum
# max = maximum

# mean = (min + max)/2

result_arr = clip(array, minimum, maximum)
print (result_arr)
plt.plot(array, result_arr)
plt.show()

但我仍然没有显示结果 plot。我需要修复什么?

你需要了解numpy.where

def clip(v, vmin, vmax):
    from numpy import where
    return where(v<vmin, vmin, where(v>vmax, vmax, v))
...
a = a_from(b, c, d) # just an example, right?
a_clipped = clip(a, amin, amax)

例如,

In [6]: def clip(v, vmin, vmax):
   ...:     from numpy import where
   ...:     return where(v<vmin, vmin, where(v>vmax, vmax, v))
   ...: 
   ...: clip(np.arange(10, 30), 15, 25)
Out[6]: 
array([15, 15, 15, 15, 15, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 25,
       25, 25, 25])

当然还有numpy.clip(a, amin, amax)但我的印象是你需要推出自己的......

根据您的“剪辑”应该做什么,这里有一些“原生 python”的想法,即没有导入(可以使用例如numpypandas.Series来完成):

#Remove all elements outside [mi,ma]
a = [1,2,3,4,5,6,7,8,9,10]
mi = 3 #min
ma = 7  #max
list(filter(lambda x: mi<x<ma,a)) # [4,5,6]
#Set elements greater than 7 to 7 and all elements less than 3 to three
def clip_to_min_max(x,mi,max):
   if x<mi: #Number is less than "mi" set it to "mi"
      return mi
   if x>ma: #Number is greater han "max", set it to "ma"
      return mx
   return x #It is between "mi" and "ma" - do nothing

[clip_to_min_max(x,3,7) for x in  a] #[3,3,3,4,5,6,7,7,7,7]

您可以按照 mozway 的建议简单地使用np.clip


首先,我们导入所需的库。

import numpy as np
import matplotlib.pyplot as plt

然后,简单地定义从用户输入中获取最小值和最大值的clip函数。

def clip(a):
    min_val, max_val = [float(input(i))
        for i in ["Minimum value: ", "Maximum value: "]]

    return np.clip(a, min_val, max_val)

之后,我用np.random.randint定义了一个任意数组。

a = np.random.randint(0, 100, 100)
x_values = np.arange(len(a))

最后,我按如下方式裁剪并绘制了两个数组。

fig, (ax1, ax2) = plt.subplots(1, 2, sharey=True, figsize=(9, 3), tight_layout=True)

ax1.plot(x_values, a)
ax1.set_title("Unclipped Array")

ax2.plot(x_values, clip(a))
ax2.set_title("Clipped Array")

plt.show()

可视化

上图是我们的最终结果。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM