## 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:

 12 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!!

## 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:

 12345 # import numpyimport numpy as npfrom numpy.random import default_rngarr =  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)

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

This should return the array stored in the binary file.

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:

 1234 arr = np.array([2,3,4])# select target indices and add 1np.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:

 1234 arr = np.array([2,3,4])# select target indices and add 1np.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.

## Numpy Np.Apply_Along_Axis

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:

 123456 # import numpyimport numpy as npdef 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.

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

This should return:

## NumPy np.quantile()

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!!!

## NumPy np.gcd()

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.

## NumPy np.cumsum()

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.

## NumPy np.clip()

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.

## NumPy np.c_

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]]

## NumPy np.outer()

In NumPy, the outer() function allows us to calculate the outer product of two vectors.

https://en.wikipedia.org/wiki/Outer_product

The outer product can be expressed as shown:

Suppose you have two vectors a and b with the values as shown:

a = [a0, a1, a2…aM]

b = [b0, b1, b2…bN]

The outer product is calculated as shown:

[[a0*b0  a0*b1 … a0*bN ]
[a1*b0    .
[ …          .
[aM*b0            aM*bN ]]

Let us learn how to use the outer() function in NumPy.

## Function Syntax

The function syntax can be expressed as shown in the code snippet below:

numpy.outer(a, b, out=None)

## Parameters

The function has a simple syntax and accepts three main parameters:

1. a – refers to the first input vector. Think of it as M in the previous explanation.
2. b – refers to the second input vector. In this case, it acts as N.
3. out – an alternative array to store the resulting output. It takes shape (M, N).

## Return Value

The function returns the outer product of the two vectors in the for:

## Example #1

The code below shows how to calculate the outer product of two one-dimensional arrays.

# import numpy
import numpy as np
a = np.array([10,20,30])
b = np.array([1,2,3])
print(np.outer(a, b))

The resulting array is as shown:

[[10 20 30]
[20 40 60]
[30 60 90]]

## Example #2

In the case of a 2×3 matrix, the function should return:

a = np.array([[10,20,30], [40,50,60]])
b = np.array([[1,2,3], [4,5,6]])
print(np.outer(a,b))

The function should return:

[[ 10  20  30  40  50  60]
[ 20  40  60  80 100 120]
[ 30  60  90 120 150 180]
[ 40  80 120 160 200 240]
[ 50 100 150 200 250 300]
[ 60 120 180 240 300 360]]

## Example #3

The outer function also allows you to perform the outer product with a vector of letters.

An example is as shown:

a = np.array([‘a’, ‘b’, ‘c’, ‘d’], dtype=object)
b = np.array([0,1,2,3])
print(np.outer(a,b))

The code above should return:

[[» ‘a’ ‘aa’ ‘aaa’]
[» ‘b’ ‘bb’ ‘bbb’]
[» ‘c’ ‘cc’ ‘ccc’]
[» ‘d’ ‘dd’ ‘ddd’]]

## Conclusion

This article guides you in calculating the outer products of two vectors using NumPy’s outer() function.

Thanks for reading & Happy coding!!