Archive d’étiquettes pour : NumPy


“In this tutorial, you will learn the various methods you can use to specify multiple conditions using the np.where() function.”

Method 1 – NumPy.where() Multiple Conditions Using the AND Operator

The where() function in NumPy allows us to select elements from a given array that match a given condition. By default, the function accepts a single condition to match against the given array of elements.

What if we need to check for multiple conditions in a given array? For that purpose, we can use Python’s logical operators to accomplish that.

One such operator is the & (AND) operator. It allows us to specify multiple conditions inside the where function and add and join them with the & operator.

The function will take all the specified conditions and return the elements that match all the conditions.

We can illustrate this with an example as shown below:

import numpy as np
arr = np.array([100,120,344,232,343,456,674,637])
new_arr = arr[np.where((arr>300) & (arr<500))]
print(new_arr)

In the program above, we start by creating an array holding a set of integers. We then create a new array and use the where the function to filter for multiple conditions. If any element in the array is greater than 300 and less than 500, add it to the new array. Finally, we print the resulting array:

python where.py
[344 343 456]

Using the & operator ensures that both of the conditions are true.

Method 2 – NumPy.where() Multiple Conditions Using the OR Operator

In some cases, you may want only one of the multiple conditions to be true. For that, we can use the OR operator. This tells the where the function to evaluate all the conditions provided and if any element in the given array matches one of them, add it to the result.

Take the example result shown below:

import numpy as np
arr = np.array([100,120,344,232,343,456,674,637])
new_arr = arr[np.where((arr>300) | (arr==500))]
print(new_arr)

In the example above, we use the | operator to specify multiple conditions and store the resulting values in the new_arr variable. If any element of the input array is greater than or equal to 500, add it to the new array.

The resulting output:

$ python where.py
[344 343 456 674 637]

We can see that all the returned elements are greater than 300.

Method 3 – Numpy.where() Multiple Conditions With Numpy.logical_and() Function

If you do not wish to use Python’s logical operators, NumPy has a logical_and() function that can replace the & operator.

The function is used to determine the element-wise truth of a value of an AND gate. Let us see how we can adopt this function to specify multiple conditions in a NumPy where() function.

import numpy as np
arr = np.array([100,120,344,232,343,456,674,637])
new_arr = arr[np.where(np.logical_and(arr>300, arr<400))]
print(new_arr)

In the code above, we start by defining an array of integers whose elements we wish to filter.

We then use the np.where() function and pass the conditions we wish to evaluate. In this case, we pass them as arguments of the np.logical_and function.

The function evaluates the conditions and filters the elements that match the specified values.

An example output is as shown:

$ python where.py
[344 343]

From the output, only two elements match the specified conditions.

Method 4 – Numpy.where() Multiple Conditions With Numpy.logical_or() Function

Similarly, NumPy has a function that performs the same task as the Python’s logical OR. The numpy.logical_or() function is used to calculate the element-wise true value of an OR gate.

For our case, we can specify multiple conditions and pass them to the np.where() function.

An example code is as shown below:

import numpy as np
arr = np.array([100,120,344,232,343,456,674,637])
new_arr = arr[np.where(np.logical_or(arr>300, arr%2==0))]
print(new_arr)

Here, the function should return all the elements that are either greater than 300 or ones that even number.

The resulting values are:

python where.py
[100 120 344 232 343 456 674 637]

It works.

Closing

That’s it for this one. In this tutorial, you learned how to specify multiple conditions in the NumPy where() function using the logical or, logical and, numpy’s logical_and function, and numpy’s logical_or function.

Thanks for reading!!



Source link


Problem

We have an array containing Boolean elements. The goal is to determine how many of those elements in the array are True.

Solution 1

The naïve approach would create a sum counter and a for loop that iterates over each element in the array. We then check if that element is true and if yes, we add it to the counter.

After completion, we get the sum variable’s value, the number of True elements in the array.

Solution 2

We can intelligently approach the problem since we are not looking at the naïve approach.

We know that Python treats a False value as 0 and any other value as True. So if that’s the case, we can use the NumPy count_nonzero() function to solve the problem.

The NumPy count_nonzero() function allows us to calculate all the non-zero values in a given array. Or, shall I say, it will enable us to count the number of True values in an array.

The function syntax is as shown:

1

numpy.count_nonzero(a, axis=None, *, keepdims=False)

Example 1

Consider the example below that uses the count_nonzero() function to determine the number of non-zero elements in the array.

arr = [1,2,0,3,4,0,5,6,7]
print(“non-zero”, np.count_nonzero(arr))

The code above should determine the number of the non-zero values and print the result as shown:

Example 2

The same case applies to Boolean values as shown in the array below:

1
2

arr = [[True, False, True], [True, False, False]]
print(«non-zero», np.count_nonzero(arr))

The output result is as shown:

And with that, we have solved our initial problem.

Conclusion

Thanks for following along with this tutorial where we covered how to use the count_nonzero() function to determine the number of True elements in an array.

Happy coding!!



Source link


This article will discuss saving and reading a NumPy array to and from a binary file.

NumPy tofile()

The NumPy tofile() function allows you to save an array to a text or binary file. Since we are interested in binary files, let us learn how we can use this function.

The function syntax is as shown:

1

ndarray.tofile(fid, sep=», format=‘%s’)

The function parameters are as illustrated below:

  1. fid – refers to an open file object or path to file.
  2. sep – specifies the separator between the array items. For binary files, this is equal to file.write(a.tobytes()) where a is the input array.
  3. Format – specifies the format string for text file output.

An example is as shown below:

1
2
3
4
5

# import numpy
import numpy as np
from numpy.random import default_rng
arr =  default_rng(24).random((3,5,3))
arr

In the example above, we have a simple program that generates an array using the random function.

The resulting array is as shown:

To save the array to a binary file using the tofile() function, we can do this:

This should create a new binary file holding the input array.

NumPy fromfile

To load the data stored in a binary file, we can use the fromfile function. The function has a syntax as shown:

1

numpy.fromfile(file, dtype=float, count=1, sep=», offset=0, *, like=None)

Check the docs for more info.

In the example, to load the file, we can run:

1
2

load_arr = np.fromfile(‘arr.bin’)
display(arr)

This should return the array stored in the binary file.



Source link


The add.at a function in NumPy allows you to perform an in-place operation on the left-side operand.

In the case of an addition operation, the function will add the right operand to the left operand at the specified array index.

The syntax is as illustrated below:

In simple terms, the function will take each element in a specified array index and add the right operand to it.

Function Syntax

The function syntax is as shown below:

1

ufunc.at(a, indices, b=None, /)

The parameters are as shown:

  1. a – refers to the input array.
  2. indices – target array index or indicies.
  3. b – refers to the right-hand operand.

Example

The code below shows how to use the add.at function to add one value to each element in an input array:

1
2
3
4

arr = np.array([2,3,4])
# select target indices and add 1
np.add.at(arr, [0,1,2], 1)
print(arr)

In the code above, we start by selecting the target indices as shown [0,1,2]. We then specify the value we wish to add to the arrays.

The code above should return:

Example #2

You can also perform an in-place subtraction as shown:

1
2
3
4

arr = np.array([2,3,4])
# select target indices and add 1
np.subtract.at(arr, [0,1,2], 1)
print(arr)

This should return:

Conclusion

This short article discussed the basics of using the ufunc at() function in NumPy.



Source link


The apply_along_axis() function is used to apply a specific function to a 1D slice along a specified axis.

Function Syntax

The function syntax is as shown:

1

numpy.apply_along_axis(func1d, axis, arr, *args, **kwargs)

The parameters are as shown:

  1. func1d – specifies the function that operates on the 1-D slices.
  2. axis – specifies along which axis the array is sliced.
  3. arr – refers to the input array.

The function returns an output array except along the axis. The axis is removed and replaced with the dimensions equal to the shape of the function return value.

 Example

To apply the mean function along the zero axis of a one-dimensional array, we can do:

1
2
3
4
5
6

# import numpy
import numpy as np
def m(a):
   return np.mean(a)
arr = np.array([10,20,20,230,23,243])
print(np.apply_along_axis(m, 0, arr))

This should calculate and return the mean of elements in the input array along the specified axis.

An example return value is as shown:

Example 2

The example below shows how function behaves in a two-dimensional array.

1
2

arr = np.array([[10,20,20],[230,23,243]])
print(np.apply_along_axis(m, 0, arr))

This should return:



Source link


As the name suggests, the quantile() function in NumPy allows you to calculate the qth quantile of the specified array along a set axis. When working with frecuente distributions, quantiles and percentiles are very fundamental concepts.

Let us explore NumPy’s quantile function.

Function Syntax

The function syntax is as shown below:

numpy.quantile(a, q, axis=None, out=None, overwrite_input=False, method=‘linear’, keepdims=False, *, interpolation=None)

Function Parameters

The function accepts the parameters as follows:

  1. a – the input array or array_like object.
  2. q – your target quantile to calculate. You can also pass an inclusive sequence of quantiles ranging from 0 to 1.
  3. axis – defines along which axis to calculate the quantile. By default, this value is set to None. Hence, the function will flatten the array and calculate the specified quantile.
  4. out – sets an output array for the result.
  5. overwrite_input – this parameter allows the function to modify the input array.
  6. method – specifies the method used in estimating the quantile. Check the docs to discover the accepted values.

Function Return Value

The function returns the qth quantile of the specified array along the set axis.

Example #1

The example shown below calculates a single quantile of a specified array.

# import numpy
import numpy as np
arr = np.array([10,20,30,40,50])
print(f«.5 quantile: {np.quantile(arr, 0.5)}»)

The code above should return the .5 quantile of the values in the provided array. The resulting output is:

Example #2

To calculate multiple quantiles of a given array, we can do:

arr = np.array([10,20,30,40,50])
print(np.quantile(arr, [0.25, 0.25, 0.50]))

The above code calculates the quantiles as specified in the sequence.

The resulting values are as shown below:

Example #3

To calculate the quantile of a 2D array along a specific axis:

arr = np.array([[9,5,3], [4,7,1]])
print(np.quantile(arr, .25, axis=0))

For example, we calculate the .25th quantile along axis 0 of the input array in the code above.

The output is as shown:

Example #4

You can also change the interpolation method as shown in the example below:

arr = np.array([[9,5,3], [4,7,1]])
print(np.quantile(arr, .25, axis=0, interpolation=‘nearest’))

This results in the following array:

Conclusion

Using this article, you should be natural with the NumPy quantile function and how to use it to calculate the qth quantiles of a given array along a specified axis.

See you at the next one!!!



Source link


We all remember GCD or Greatest Common Divisor in Elementary Mathematics. However, in this tutorial, we will learn how to simplify the manual GCD calculation using a simple function in NumPy.

Let us take back our time.

Function Syntax

GCD or Greatest Common Divisor is the greatest positive value that can divide two or more numbers.

The gcd function in NumPy has a syntax as shown:

numpy.gcd(x1, x2, /, out=None, *, where=True, casting=‘same_kind’, order=‘K’, dtype=None, subok=True[, signature, extobj]) = <ufunc ‘gcd’>

Despite the crazy-looking syntax, you only need to worry about two parameters, as shown:

  1. x1 and x2 – refer to the input arrays.

Example #1

The code below shows using the gcd() function with two scalar values.

# import numpy
import numpy as np
print(f«gcd: {np.gcd(130, 13)}»)

The above code should return the GCD of 130 and 13 as shown:

Example #2

To get the GCD of two arrays, we can do:

arr_1 = np.array([11,12,13])
arr_2 = np.array([14,145,15])
print(f«gcd: {np.gcd(arr_1, arr_2)}»)

The code above should return:

Example #3

You can also determine the GCD of an element of arrays and a scalar value. For example:

arr = np.array([14,145,15])
print(f«GCD: {np.gcd(arr, 5)}»)

The example code above should return the GCD of the array, and 5.

Closing

This tutorial walks through how to calculate the GCD of array elements along a given axis.

Thanks for reading!!



Source link


The cumsum() function in NumPy allows you to calculate the cumulative sum of elements along a given axis.

Let us explore.

Function Syntax

The function syntax is as shown below:

numpy.cumsum(a, axis=None, dtype=None, out=None)

Function Parameters

The function returns the parameters as shown:

  1. a – refers to the input array.
  2. axis – along which axis the cumulative sum is performed.
  3. dtype – specifies the data type of the output.
  4. out – specifies the output array to store the result.

Function Return Value

The function returns a new array with the cumulative sum of the input array elements.

Example #1

The code below shows how to calculate the cumulative sum of a two-dimensional array along the None axis.

# import numpy
import numpy as np
arr = np.array([[1,2,3], [4,5,6]])
print(f«result: {np.cumsum(arr, axis=None)}»)

The code above should flatten the array and an array holding the cumulative sum of the elements.

An example output is as shown:

result: [ 1  3  6 10 15 21]

Example #2

The following example shows how to use the cumsum() function along the zero axis.

arr = np.array([[1,2,3], [4,5,6]])
print(f«result: {np.cumsum(arr, axis=0)}»)

This should return:

result:
[[1 2 3]
 [5 7 9]]

Example #3

Along the axis=1, the function returns the result as:

arr = np.array([[1,2,3], [4,5,6]])
print(f«result: {np.cumsum(arr, axis=1)}»)

The output array is as shown:

result:
[[ 1  3  6]
 [ 4  9 15]]

Conclusion

Using this article, you learned how to calculate the cumulative sum of elements along a given axis in an input array using the cumsum() function. Feel free to explore the docs for more.

Thanks for reading!!



Source link


This article will explore the clip() function in NumPy. We will start with the function syntax, its parameters, and examples of using the function.

The clip() function in NumPy allows you to limit the values passed to it by specifying the min and max range values.

Function Syntax

The function syntax is as shown below:

numpy.clip(a, a_min, a_max, out=None, **kwargs)

Parameter Values

The function accepts the following parameters:

  1. a – refers to the input array.
  2. a_min – the minimum value that can be inserted in the array.
  3. a_max – the maximum value accepted by the array.
  4. out – specifies an output array to store the result.

Return Value

The function will return an array with the specified elements of the input array. Any values less than a_min are replaced with a_min, while values greater than a_max are replaced with a max.

For example, if a_min = 1 and a_max = 1, values less than one are replaced with one and values greater than ten are replaced with 10.

Example #1

Consider the example shown below:

# import numpy
import numpy as np

arr = np.array([[1,2,3], [4,5,6]])
print(f«before:n{arr}»)
arr_clip = np.clip(arr, a_min=1, a_max=5)
print(f«after:n{arr_clip}»)

In this example, we have an array with values ranging from 1 to 6. We then use the clip function and set the min value to 1 and the max value to 5.

Since six is greater than the max value, the function will replace it with five and return the array as shown:

Example #2

You can also pass an array to the a_min or a_max parameters. Consider the example below:

arr = np.array([[1,2,3], [4,5,6], [7,8,9], [10,11,12]])
print(f«before:n{arr}»)
arr_clip = np.clip(arr, a_min=[1,2,3], a_max=6)
print(f«after:n{arr_clip}»)

The code above should return:

Conclusion

In this article, we discussed the clip function in NumPy and how to use it to limit the minimum and maximum values an array can accept.

Thanks for reading!!



Source link


The NumPy np.c_ is part of the NumPy’s indexing routines that allow you to concatenate an array along the second axis.

Let us explore how this routine works and how we can use it.

Syntax

The syntax of the numpy c_ routine is as shown below:

Return Value

The routine does not take any parameters except the arrays that you need to concatenate.

It will then return the concatenated array along the second axis.

Example Illustration

The example below illustrates how to use the np.c_ to concatenate two arrays.

# import numpy
import numpy as np
# create an array
arr1 = np.array([1,2,3])
arr2 = np.array([7,8,9])
print(np.c_[arr1, arr2])

In this example, the np.c_ routine takes the arrays and concatenates them along the second axis.

NOTE: When talking about the second axis, we refer to the axis=1 or the column axis.

The code above should return an array as:

In this case, the np.c_ takes two one-dimensional arrays and concatenates them to form a two-dimensional array.

Example #2

Let us see what happens when we apply the routine in 2d arrays.

arr1 = np.array([[1,2,3,4], [5,6,7,8]])
arr2 = np.array([[9,10,11,12], [13,14,15,16]])
print(np.c_[arr1, arr2])

The code snippet above should return:

[[ 1  2  3  4  9 10 11 12]
 [ 5  6  7  8 13 14 15 16]]

Closing

This article aims to help you understand NumPy’s indexing routine np.c_ and how to use it.

Thanks for reading!!!



Source link