Home > Enterprise >  How to clip an array to the minimum and maximum without using loops
How to clip an array to the minimum and maximum without using loops

Time:10-26

I am still learning python, and I am writing a code to clip an array to the minimum and the maximum value, but without using any loops.

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()

But I still does not show the result plot. What do I need to fix?

CodePudding user response:

Based on what your "clipping" should do, here's some idea with "native python" i.e no imports (can be done otherwise using e.g numpy or pandas.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]

CodePudding user response:

You need to know about Visualization

The above plot is our final result.

  • Related