Reduce array's dimension by one but initialize the reduction with a different value in Numpy


To reduce array’s dimension by one, use the np.ufunc.reduce() method in Python Numpy. Here, we have used add.reduce() to reduce it to the addition of all the elements. To initialize the reduction with a different value, use the "initials" parameter.

A universal function (or ufunc for short) is a function that operates on ndarrays in an element-byelement fashion, supporting array broadcasting, type casting, and several other standard features. That is, a ufunc is a "vectorized" wrapper for a function that takes a fixed number of specific inputs and produces a fixed number of specific outputs

Steps

At first, import the required library −

import numpy as np

Create a 1D array −

arr = np.array([7, 14, 21, 28, 35])

Display the array −

print("Array...
", arr)

Get the type of the array −

print("
Our Array type...
", arr.dtype)

Get the dimensions of the Array −

print("
Our Array Dimensions...
",arr.ndim)

To reduce array’s dimension by one, use the np.ufunc.reduce() method in Python Numpy. Here, we have used add.reduce() to reduce it to the addition of all the elements. To initialize the reduction with a different value, use the "initials" parameter −

print("
Result (addition)...
",np.add.reduce(arr, initial = 99))

Example

import numpy as np

# The numpy.ufunc has functions that operate element by element on whole arrays.
# ufuncs are written in C (for speed) and linked into Python with NumPy’s ufunc facility

# Create a 1D array
arr = np.array([7, 14, 21, 28, 35])

# Display the array
print("Array...
", arr) # Get the type of the array print("
Our Array type...
", arr.dtype) # Get the dimensions of the Array print("
Our Array Dimensions...
",arr.ndim) # To reduce array’s dimension by one, use the np.ufunc.reduce() method in Python Numpy # Here, we have used add.reduce() to reduce it to the addition of all the elements # To initialize the reduction with a different value, use the "initials" parameter print("
Result (addition)...
",np.add.reduce(arr, initial = 99))

Output

Array...
[ 7 14 21 28 35]

Our Array type...
int64

Our Array Dimensions...
1

Result (addition)...
204

Updated on: 08-Feb-2022

156 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements