Home > Blockchain >  Min and max values of an array in Python
Min and max values of an array in Python

Time:12-03

I want to calculate the minimum and maximum values of array A but I want to exclude all values less than 1e-12. I present the current and expected outputs.

import numpy as np
A=np.array([[9.49108487e-05],
       [1.05634586e-19],
       [5.68676707e-17],
       [1.02453254e-06],
       [2.48792902e-16],
       [1.02453254e-06]])

Min=np.min(A)
Max=np.max(A)
print(Min,Max)

The current output is

1.05634586e-19 9.49108487e-05

The expected output is

1.02453254e-06 9.49108487e-05

CodePudding user response:

Slice with boolean indexing before getting the min/max:

B = A[A>1e-12]
Min = np.min(B)
Max = np.max(B)
print(Min, Max)

Output: 1.02453254e-06 9.49108487e-05

B: array([9.49108487e-05, 1.02453254e-06, 1.02453254e-06])

CodePudding user response:

You can just select the values of the array greater than 1e-12 first and obtain the min and max of that:

>>> A[A > 1e-12].min()
1.02453254e-06
>>> A[A > 1e-12].max()
9.49108487e-05

CodePudding user response:

To exclude values less than 1e-12 from the minimum and maximum calculation, you can use the where function from NumPy to select only the values that are greater than or equal to 1e-12, and then use the min and max functions to find the minimum and maximum values of the resulting array.

Here is an example of how you can do this:

import numpy as np

# Define the array A
A = np.array([[9.49108487e-05],
              [1.05634586e-19],
              [5.68676707e-17],
              [1.02453254e-06],
              [2.48792902e-16],
              [1.02453254e-06]])

# Use the where function to select only the values that are greater than or equal to 1e-12
A_filtered = np.where(A >= 1e-12, A, np.nan)

# Use the min and max functions to find the minimum and maximum values
Min = np.min(A_filtered)
Max = np.max(A_filtered)

# Print the results
print(Min, Max)

This should give you the expected output of 1.02453254e-06 9.49108487e-05.

CodePudding user response:

arr = np.array([9.49108487e-05,1.05634586e-19,5.68676707e-17,1.02453254e-06,2.48792902e-16,1.02453254e-06]) 
mask = arr > 1e-12 
Min = np.min(arr[mask]) 
Max = np.max(arr[mask])
  • Related