Python NumPy compress() is an inbuilt function that returns selected slices of an array along a given axis. The compress() function defined under NumPy, which can be imported as import NumPy as np, and we can create multidimensional arrays and derive other mathematical statistics with the help of NumPy, which is a library in Python. […]

The post Python NumPy compress() Function Example appeared first on AppDividend.

]]>Python NumPy compress() is an inbuilt function that returns selected slices of an array along a given axis. The compress() function defined under NumPy, which can be imported as import NumPy as np, and we can create multidimensional arrays and derive other mathematical statistics with the help of NumPy, which is a library in Python.

When working along a given axis, a slice along that axis is returned in output for each index where condition evaluates to True. The above explanation works in case of the 2D array, and when working on a 1-D array, compress is equivalent to extract function.

**Python NumPy** **compress()** function returns the selected slices of an array along the given axis. When working along a given axis, a slice along that axis is returned in output for each index where condition evaluates to True.

numpy.compress (condition, input_array, axis = None, out = None)

**condition:**It depicts the condition based on which user extract elements. On applying a condition to the input_array, it returns an array filled with either True or False and after those input_Array elements are extracted from the Indices having True value.**Input_array:**It depicts the input array in which the user applies conditions on its elements**axis:**It Indicates which slice the user wants to select. It is entirely optional, and by default, it works on flattened array[1-D].**out:**It depicts the Output_array with elements of input_array, that satisfies the condition. It is an entirely optional parameter.

The compress() function returns the copy of array elements that are satisfied according to the given conditions along the given axis.

import numpy as np array = np.arange(10).reshape(5, 2) print("Original array : \n", array) a = np.compress((array > 0)[1], array, axis=0) print("\nSliced array : \n", a)

Original array : [[0 1] [2 3] [4 5] [6 7] [8 9]] Sliced array : [[0 1] [2 3]]

In the above code, according to the condition, elements in the row greater than 0 slices were returned along the 0 axis.

See the following code.

import numpy as np array = np.arange(10).reshape(5, 2) print("Original array : \n", array) a = np.compress([True, False], array, axis=1) print("\nSliced array : \n", a)

Original array : [[0 1] [2 3] [4 5] [6 7] [8 9]] Sliced array : [[0] [2] [4] [6] [8]]

In the above code Boolean list was passed as a condition, so along the 1 axis, all the elements were extracted from the 1st column.

The post Python NumPy compress() Function Example appeared first on AppDividend.

]]>Python NumPy rot90() is an inbuilt function that is used for rotating the elements of an array by 90 degrees along a specified axis. The rot90() can be imported as import NumPy as np, and we can create multidimensional arrays and derive other mathematical statistics with the help of NumPy, which is a library in […]

The post Python NumPy rot90() Function Example appeared first on AppDividend.

]]>Python NumPy rot90() is an inbuilt function that is used for rotating the elements of an array by 90 degrees along a specified axis. The rot90() can be imported as import NumPy as np, and we can create multidimensional arrays and derive other mathematical statistics with the help of NumPy, which is a library in Python.

The **rot90()** function is used to rotate the array by 90 degrees in the plane specified by axes. The rotation direction is from the first towards a second axis. An array of two or more dimensions. The number of times an array is rotated by 90 degrees.

numpy.rot90 (input_array, k = 1, axes = (0, 1))

- Input_array: It depicts the n-dimensional array where rotation is to be performed.
- k: It represents the number of times we wish to rotate array by 90 degrees.
- axes: It depicts the plane along which we want to rotate the array.

It returns the rotated version of the input_array.

See the following code.

import numpy as np array = np.arange(12).reshape(3, 4) print("Original array : \n", array) # Rotating once print("\nRotated array : \n", np.rot90(array)) # Rotating twice print("\nRotated array : \n", np.rot90(array, 2))

Original array : [[ 0 1 2 3] [ 4 5 6 7] [ 8 9 10 11]] Rotated array : [[ 3 7 11] [ 2 6 10] [ 1 5 9] [ 0 4 8]] Rotated array : [[11 10 9 8] [ 7 6 5 4] [ 3 2 1 0]]

In the above code, Function 1 was used to rotate the array in 90 degrees only one time.

Function 2 was used to rotate the array in 90 degrees two times.

See the second example.

import numpy as np m = np.arange(8).reshape((2, 2, 2)) print("Original Array\n") print(m) print("Rotated Array\n") print(np.rot90(m, 1, (1, 2)))

Original Array [[[0 1] [2 3]] [[4 5] [6 7]]] Rotated Array [[[1 3] [0 2]] [[5 7] [4 6]]]

In the above code, function rotated the input array along (1, 2) place only one time.

**Note:** The numpy.rot90() returns the view. Because a view shares memory with an original array, changing one value changes the other.

Specifying the integer value for a second argument k rotates the array 90 degrees counterclockwise k times. See the following code.

import numpy as np m = np.arange(8).reshape((2, 2, 2)) print("Original Array\n") print(m) print("Rotated Array\n") print(np.rot90(m, 10)) print("Rotated Array 2nd time\n") print(np.rot90(m, 11)) print("Rotated Array 3rd time\n") print(np.rot90(m, 21))

Original Array [[[0 1] [2 3]] [[4 5] [6 7]]] Rotated Array [[[6 7] [4 5]] [[2 3] [0 1]]] Rotated Array 2nd time [[[4 5] [0 1]] [[6 7] [2 3]]] Rotated Array 3rd time [[[2 3] [6 7]] [[0 1] [4 5]]]

NumPy rot90() function is used to rotate the array by 90 degrees in the plane specified by axes. The rotation direction is from the first towards the second axis.

The post Python NumPy rot90() Function Example appeared first on AppDividend.

]]>Python NumPy ravel() is an inbuilt NumPy function that can be imported as import NumPy as np, and we can create multidimensional arrays and derive other mathematical statistics. The ravel() function is used for returning a 1D array containing all the elements of the n-dimensional input array. If you want to flatten the array then […]

The post Python NumPy ravel() Function Example appeared first on AppDividend.

]]>Python NumPy ravel() is an inbuilt NumPy function that can be imported as import NumPy as np, and we can create multidimensional arrays and derive other mathematical statistics. The ravel() function is used for returning a 1D array containing all the elements of the n-dimensional input array. If you want to flatten the array then use the numpy ravel() function.

**Python numpy**.**ravel**(array, order = ‘C’) function returns a contiguous flattened array(1D array with all the input-array elements and with the same type as it). A copy is made only if needed.

numpy.ravel(a, order='C')

**a:**This parameter depicts the Input array in which the elements are read in the order specified by an order which gets further packed as a 1D array.**order:**The order argument can be either C_contiguous or F_contiguous, where C order operates row-rise on the array, and F order operates the column-wise operations.

The ravel() function returns the 1D array containing all the elements of input array with shape (a.size ()).

Program to show the working of ravel function.

import numpy as np arr = np.arange(6).reshape(3, 2) print('The original array:') print(arr, "\n") print('After applying ravel function:') print(arr.ravel()) #Maintaining F order print('ravel function in F-style ordering:') print(arr.ravel(order='F')) #K-order preserving the ordering print("\nnumpy.ravel() function in K-style ordering: ", arr.ravel(order='K'))

The original array: [[0 1] [2 3] [4 5]] After applying ravel function: [0 1 2 3 4 5] ravel function in F-style ordering: [0 2 4 1 3 5] numpy.ravel() function in K-style ordering: [0 1 2 3 4 5]

Here, in the above code, 1st function was used to create a 1D array in which no order was given due to which K type of order was used by default.

2nd function was used to create a 1D array in which F-style ordering was used in which elements are inserted in the array column-wise.

3rd function was used to create a 1D array in which F-style ordering was used in which elements are inserted in the array row-wise.

See the following second code.

import numpy as np arr = np.arange(6).reshape(3, 2) print("Array: \n", arr) # calling the numpy.ravel() function print("\nravel() value: ", arr.ravel()) # ravel() is equivalent to reshape(-1, order=order). print("\nnumpy.ravel() == numpy.reshape(-1)") print("Reshaping array : ", arr.reshape(-1))

Array: [[0 1] [2 3] [4 5]] ravel() value: [0 1 2 3 4 5] numpy.ravel() == numpy.reshape(-1) Reshaping array : [0 1 2 3 4 5]

Here, in the above code,1st function was used to create a 1D array in which no order was given due to which K type of order was used by default.

2nd function was used to create a 1D array using reshape function in which (-1) was passed as an argument which behaves equally as of K type ordering in ravel function.

NumPy ravel() function returns the flattened one-dimensional array. The copy is made only if needed. The returned array will have the same type as that of an input array.

The post Python NumPy ravel() Function Example appeared first on AppDividend.

]]>Python NumPy reshape() is an inbuilt NumPy function that can be imported as import NumPy as np, and we can create multidimensional arrays and derive other mathematical statistics. NumPy reshape() function is used for giving new shape to an array without changing its elements. Python NumPy reshape() Python numpy.reshape(array, shape, order = ‘C’) function shapes […]

The post Python NumPy reshape() Function Example appeared first on AppDividend.

]]>Python NumPy reshape() is an inbuilt NumPy function that can be imported as import NumPy as np, and we can create multidimensional arrays and derive other mathematical statistics. NumPy reshape() function is used for giving new shape to an array without changing its elements.

Python numpy.reshape(array, shape, order = ‘C’) function shapes an array without changing data of array.

numpy.reshape (a, newshape, order='C')

**array:**This depicts the input_array whose shape is to be changed.**shape:**This represents int value or tuples of int.**order:**This parameter represents the order of operations. It can be either C_contiguous or F_contiguous, where C order operates row-rise on the array, and F order operates column-wise operations.

The NumPy reshape() function returns an array with a new shape having its contents unchanged.

Program to show the working of the reshape() function.

import numpy as np array = np.arange(6) print("Array Value: \n", array) # array reshaped with 3 rows and 2 columns array = np.arange(6).reshape(3, 2) print("Array reshaped with 3 rows and 2 columns : \n", array) # array reshaped with 2 rows and 3 columns array = np.arange(6).reshape(2, 3) print("Array reshaped with 2 rows and 3 columns : \n", array)

Array Value: [0 1 2 3 4 5] Array reshaped with 3 rows and 2 columns : [[0 1] [2 3] [4 5]] Array reshaped with 2 rows and 3 columns : [[0 1 2] [3 4 5]]

In the above code original array was a 1D array.

So, in the 1st function, the array was modified to 3 rows and two columns.

In the 2nd function, the array was modified to 2 rows and three columns.

In the above function, the array gets reshaped only when the size of the array is equal to the multiplication of rows and columns. If not, then the shell will prompt an error.

See the following code.

import numpy as np x = np.array([[21, 11, 19], [46, 18, 21]]) data = np.reshape(x, (2, -2)) print(data)

[[21 11 19] [46 18 21]]

Take the following one-dimensional NumPy array ndarray as the example.

# app.py import numpy as np arr = np.arange(12) print('The array is:', arr) print('The shape of array is:', arr.shape) print('The dimension of array is:', arr.ndim)

The array is: [ 0 1 2 3 4 5 6 7 8 9 10 11] The shape of array is: (12,) The dimension of array is: 1

Specify the converted shape as the list or tuple in the first argument of the reshape() method of numpy.ndarray.

See the following code.

import numpy as np arr = np.arange(12) print('The array is:', arr) print('The shape of array is:', arr.shape) print('The dimension of array is:', arr.ndim) arr_3_4 = arr.reshape([3, 4]) print(arr_3_4) print('The dimension is: ', arr_3_4.ndim) print('The shape is: ', arr_3_4.shape)

The array is: [ 0 1 2 3 4 5 6 7 8 9 10 11] The shape of array is: (12,) The dimension of array is: 1 [[ 0 1 2 3] [ 4 5 6 7] [ 8 9 10 11]] The dimension is: 2 The shape is: (3, 4)

First, we have defined an array then print the shape and dimension of the array.

Then, we have reshaped the array in the form of [3, 4] and then print the dimension and the shape of the array. If the shape does not match the number of items in the original array, then ValueError will be thrown.

In the numpy.reshape() function, specify an original numpy.ndarray as the first argument, and the shape to convert to the second argument as the list or tuple.

If the shape does not match the number of items in an original array, the ValueError will occur.

The post Python NumPy reshape() Function Example appeared first on AppDividend.

]]>Python NumPy zeros_like() is an inbuilt NumPy function that is used to return an array of similar shapes and sizes with values of elements of array replaced with zeros. The zeros_like() function is defined under numpy, which can be imported as the import numpy as np and we can create the multidimensional arrays and derive […]

The post Python NumPy zeros_like() Function Example appeared first on AppDividend.

]]>Python NumPy zeros_like() is an inbuilt NumPy function that is **used to return an array of similar shapes and sizes with values of elements of array replaced with zeros.** The zeros_like() function is defined under numpy, which can be imported as the import numpy as np and we can create the multidimensional arrays and derive other mathematical statistics with the help of numpy, which is the library in Python.

NumPy zeros_like() function returns an array of zeros with the same shape and type as a given array. The shape and data-type of a define these same attributes of the returned array.

numpy.zeros_like(array, dtype, order, subok)

The zeros_like() function takes four parameters, out of which two parameters are optional.

The first parameter is the input array.

The second parameter is the subok parameter, which is optional; it takes Boolean values, and if it is true, the newly created array will be sub-class of the main array, and if it is false, it will be a base-class array.

The third parameter is the order, which represents the order in the memory.

The fourth parameter is dtype, which is optional and, by default, has the value float. It is the data type of the returned array.

The zeros_like() function returns an array with element values as zeros.

import numpy as np arr1 = np.arange(9).reshape(3, 3) print("Original arr1 : \n", arr1) arr2 = np.zeros_like(arr1, float) print("\nMatrix arr2 : \n", arr2)

Original arr1 : [[0 1 2] [3 4 5] [6 7 8]] Matrix arr2 : [[0. 0. 0.] [0. 0. 0.] [0. 0. 0.]]

In the above example, we can see that by passing a 3×3 array, we are returning a new array with all its element value as 0, preserving the shape and size of the initial array.

import numpy as np arr1 = np.arange(16).reshape(4, 4) print("Original arr1 : \n", arr1) arr2 = np.zeros_like(arr1, float) print("\nMatrix arr2 : \n", arr2)

Original arr1 : [[ 0 1 2 3] [ 4 5 6 7] [ 8 9 10 11] [12 13 14 15]] Matrix arr2 : [[0. 0. 0. 0.] [0. 0. 0. 0.] [0. 0. 0. 0.] [0. 0. 0. 0.]]

In the above example, we can see that by passing a 4×4 array, we are returning a new array with all its element value as 0, preserving the shape and size of the initial array.

The post Python NumPy zeros_like() Function Example appeared first on AppDividend.

]]>Python NumPy ones() is an inbuilt function that is used to return an array of similar shape and size with values of elements of the array as ones. The NumPy ones() function is defined under numpy, which can be imported as import numpy as np and we can create multidimensional arrays and derive other mathematical […]

The post Python NumPy ones() Function Example appeared first on AppDividend.

]]>Python NumPy ones() is an inbuilt function that is **used to return an array of similar shape and size with values of elements of the array as ones.** The NumPy ones() function is defined under numpy, which can be imported as import numpy as np and we can create multidimensional arrays and derive other mathematical statistics with the help of numpy, which is a library in Python.

**Python numpy**.**ones()** function returns the new array of given shape and data type, where the element’s value is set to 1. The ones() function is very similar to numpy zeros() function.

numpy.ones(shape, dtype, order)

It takes three parameters, out of which one parameter is optional.

The first parameter is the shape; it is an integer or a sequence of integers.

The second parameter is the order, which represents the order in the memory, such as C_contiguous or F_contiguous.

The third parameter is optional and is the datatype of the returning array. By default, it is float.

NumPy ones() function returns an array with element values as ones.

import numpy as np arr1 = np.ones([2, 2], dtype=int) print("Matrix arr1 : \n", arr1) arr2 = np.ones([3, 3], dtype=int) print("\nMatrix arr2 : \n", arr2)

Matrix arr1 : [[1 1] [1 1]] Matrix arr2 : [[1 1 1] [1 1 1] [1 1 1]]

In this example, we can see that by taking an array and using ones(), we get all the values of the matrix as 1.

See the following code.

import numpy as np arr1 = np.ones(4, dtype=int) print("Matrix arr1 : \n", arr1)

Matrix arr1 : [1 1 1 1]

In the above example, we can see that just passing 4 as the first parameter, and we get a single row with 5 elements than by using ones(), we fix every element value as 1.

The post Python NumPy ones() Function Example appeared first on AppDividend.

]]>Python NumPy zeros() is an inbuilt function that is used to return an array of the similar shape and size with values of elements of the array as zeros. It is defined under NumPy, which can be imported as import numpy as np, and we can create multidimensional arrays and derive other mathematical statistics with […]

The post Python NumPy zeros() Function Example appeared first on AppDividend.

]]>Python NumPy zeros() is an inbuilt function that is **used to return an array of the similar shape and size with values of elements of the array as zeros.** It is defined under NumPy, which can be imported as import numpy as np, and we can create multidimensional arrays and derive other mathematical statistics with the help of NumPy, which is a library in Python.

Python NumPy zeros() function is used to get a new array of given shape and type, filled with zeros.

numpy.zeros(shape, dtype, order)

It takes three parameters out of which one parameter is optional.

The first parameter is the shape; it is an integer or a sequence of integers.

The second parameter is the order, which represents the order in the memory, such as C_contiguous or F_contiguous.

The third parameter is optional and is the datatype of the returning array. By default, it is float.

The zeros() function returns an array with element values as zeros.

import numpy as np arr1 = np.zeros(4, dtype=int) print("Matrix arr1 : \n", arr1) arr2 = np.zeros([2, 2], dtype=int) print("\nMatrix arr2 : \n", arr2) arr3 = np.zeros([3, 3]) print("\nMatrix arr3 : \n", arr3)

Matrix arr1 : [0 0 0 0] Matrix arr2 : [[0 0] [0 0]] Matrix arr3 : [[0. 0. 0.] [0. 0. 0.] [0. 0. 0.]]

In this example, we can see that after passing the shape of the matrix, we are getting zeros as its element by using numpy zeros(). 1st example is 1×4, and all values filled with zeros the same as the other two matrices.

See the following code.

import numpy as np arr1 = np.zeros([4, 4], dtype=int) print("Matrix arr1 : \n", arr1)

Matrix arr1 : [[0 0 0 0] [0 0 0 0] [0 0 0 0] [0 0 0 0]]

In the above example, we can see that by passing a 4×4 matrix, we are getting a matrix of 16 elements with all its values 0.

The post Python NumPy zeros() Function Example appeared first on AppDividend.

]]>Python NumPy empty_like() is an inbuilt NumPy function that is used to return an array of the similar shape and size as of the given array. The empty_like() function is defined under NumPy, which can be then imported as import numpy as np, and we can create multidimensional arrays and derive other mathematical statistics with […]

The post Python NumPy empty_like() Function Example appeared first on AppDividend.

]]>Python NumPy empty_like() is an inbuilt NumPy function that is **used to return an array of the similar shape and size as of the given array. **The empty_like() function is defined under NumPy, which can be then imported as import numpy as np, and we can create multidimensional arrays and derive other mathematical statistics with the help of numpy, which is a library in Python.

The **empty_like()** function is used to create the new array with the same shape and type as the given array. The shape and data-type of the prototype define these same attributes of the returned array. Overrides the data type of the result. Overrides the memory layout of the result.

numpy.empty_like(shape, order, dtype, subok )

It takes four parameters out of which 2 parameters are optional.

The first parameter is a shape, which represents the number of rows.

The second parameter is an order, which represents the order in the memory. (C_contiguous or F_contiguous).

The third parameter is the data type of the returned array. It is optional and has float value by default.

The fourth parameter is the bool parameter, which checks if we have to create the sub-class of the main array or not.

It returns the ndarray of the same shape and size.

See the following code.

import numpy as np data = ([11, 21, 31], [41, 51, 61]) res = np.empty_like(data, dtype = int) print("\nMatrix a : \n", res)

Matrix a : [[ 0 8070450532519613870 3] [1152921504878529630 4389732354 844429277641968]] (pythonenv) ➜ pyt python3 app.py Matrix a : [[ 0 -6917529027371110877 4384751619] [-3989008509232810629 4341794864 844429274149216]] (pythonenv) ➜ pyt python3 app.py Matrix a : [[ 0 3458764514091079160 4397793283] [ 0 0 844424930131968]] (pythonenv) ➜ pyt python3 app.py Matrix a : [[ 0 0 4397793283] [ 0 0 844424930131968]] (pythonenv) ➜ pyt python3 app.py Matrix a : [[ 0 -6917529027371101703 -65533] [ -4319685977 5572452860762084442 844429260842912]] (pythonenv) ➜ pyt python3 app.py Matrix a : [[ 0 -6917529027369495209 4397793283] [ 0 0 844424930131968]]

Every time you run the program, you will get a different output.

It returns the array of the same size and shape.

See the following code.

import numpy as np arr = np.empty_like([4, 4], dtype=int) print("\nMatrix arr : \n", arr) mArr = arr = ([12, 23, 43, 33], [46, 15, 61, 1], [3, 4, 6, 7], [66, 31, 35, 73]) print("\nMatrix mArr : \n", np.empty_like(mArr))

python3 app.py Matrix arr : [0 0] Matrix mArr : [[ 0 8070450532519054664 -9223372036854775800 0] [ 4294967296 0 0 0] [ 35871566856192 5572452859464646656 0 0] [ -1 -4338070505 5572452860762084442 2251799813685248]]

In this example, we can see bypassing a 4×4 matrix we get values of the same shape and size of the provided matrix.

The post Python NumPy empty_like() Function Example appeared first on AppDividend.

]]>Python NumPy empty() is an inbuilt NumPy function that is used to return an array of similar shape and size with random values as its entries. It is defined under numpy, which can be imported as import numpy as np, and we can create multidimensional arrays and derive other mathematical statistics with the help of […]

The post Python NumPy empty() Function Example appeared first on AppDividend.

]]>Python NumPy empty() is an inbuilt NumPy function that is **used to return an array of similar shape and size with random values as its entries.** It is defined under numpy, which can be imported as import numpy as np, and we can create multidimensional arrays and derive other mathematical statistics with the help of numpy, which is a library in Python.

The empty() function is used to create a new array of given shape and type, without initializing entries.

numpy.empty(shape,dtype,order)

It takes 3 parameters out of which 1 parameter is optional.

The first parameter is the shape; it is an integer or a sequence of integers, or we can say several rows.

The second parameter is the order, which represents the order in the memory, such as C_contiguous or F_contiguous.

The third parameter is optional and is the datatype of the returning array. By default, it is float.

The empty() function returns an array with random values of its entries.

import numpy as np mat1 = np.empty(4, dtype=int) print("Matrix mat1 : \n", mat1) mat2 = np.empty([3, 3], dtype=int) print("\nMatrix mat2 : \n", mat2) mat3 = np.empty([2, 2]) print("\nMatrix mat3 : \n", mat3)

Matrix mat1 : [16843009 16843009 16843009 16843009] Matrix mat2 : [[1 2 3] [4 5 6] [9 8 7]] Matrix mat3 : [[5.77068674e-321 5.81743661e+180] [6.01334412e-154 1.73303925e+097]]

In this example, we can see that bypassing the shape of the matrix and using the empty() function, and we are getting random values of the matrix.

See the following code.

import numpy as np a = np.empty([4, 4]) print("\nMatrix mat3 : \n", a)

Matrix a : [[6.23042070e-307 4.67296746e-307 1.69121096e-306 6.23058707e-307] [2.22522597e-306 1.33511969e-306 1.37962320e-306 9.34604358e-307] [9.79101082e-307 1.78020576e-306 1.69119873e-306 2.22522868e-306] [1.24611809e-306 8.06632139e-308 1.60221208e-306 2.29178686e-312]]

In the above example, we can see that when we passed a 4×4 matrix, we are getting random values as the entries of the matrix.

The post Python NumPy empty() Function Example appeared first on AppDividend.

]]>Python NumPy tri() is an inbuilt function that is used to create an array that contains 1’s at and below a given diagonal (k in this case) and 0’s at all another place of the array. It is defined under numpy, which can be imported as import numpy as np and we can create multidimensional […]

The post Python NumPy tri() Function Example appeared first on AppDividend.

]]>Python NumPy tri() is an inbuilt function that is used to create an array that contains 1’s at and below a given diagonal (k in this case) and 0’s at all another place of the array**.** It is defined under numpy, which can be imported as import numpy as np and we can create multidimensional arrays and derive other mathematical statistics with the help of numpy, which is a library in Python.

**Python numpy** **tri()** function creates an array with 1’s at and below the given diagonal(about k), and 0’s elsewhere.

numpy.tri(rows, columns, k, dtype)

The tri() function takes four parameters, out of which three parameters are optional.

The first parameter represents the number of rows the second parameter is for the number of columns, and by default, it is equal to the number of rows.

The third parameter is the k, which is an integer value and is 0 by default. If the value of k>0, then it means diagonal is above the main diagonal and, if not vice versa, follows.

The fourth parameter is **dtype,** which is also optional to mention by default, it takes float. (It is the data type of the returned array).

The tri() function returns an array with values as 1’s and 0’s.

import numpy as np print("tri with 3 rows 3 col and k=1 : \n", np.tri(3, 3, 1, dtype=float), "\n") print("tri with 3 rows and 5 columns considering main diagonal : \n", np.tri(3, 5, 0), "\n") print("tri with 3 rows and 5 columns and k=-1: \n", np.tri(3, 5, -1), "\n")

tri with 3 rows 3 col and k=1 : [[1. 1. 0.] [1. 1. 1.] [1. 1. 1.]] tri with 3 rows and 5 columns considering main diagonal : [[1. 0. 0. 0. 0.] [1. 1. 0. 0. 0.] [1. 1. 1. 0. 0.]] tri with 3 rows and 5 columns and k=-1: [[0. 0. 0. 0. 0.] [1. 0. 0. 0. 0.] [1. 1. 0. 0. 0.]]

In this example, we can see that we have taken different numbers of rows and columns, and we are getting 1s and 0s accordingly with the varying value of k, which is 1 for the 1st example 0 for second and -1 for third.

See the following code.

import numpy as np print("tri with 4 rows 4 col and k=1 : \n", np.tri(4, 4, 1, dtype=float), "\n")

tri with 4 rows 4 col and k=1 : [[1. 1. 0. 0.] [1. 1. 1. 0.] [1. 1. 1. 1.] [1. 1. 1. 1.]]

In this example, we can see that bypassing 4×4, and we are getting a 4×4 array with zeros above the main diagonal because of k value, which is passed equally to 1 over here.

The post Python NumPy tri() Function Example appeared first on AppDividend.

]]>