×

Python Tutorial

Python Basics

Python I/O

Python Operators

Python Conditions & Controls

Python Functions

Python Strings

Python Modules

Python Lists

Python OOPs

Python Arrays

Python Dictionary

Python Sets

Python Tuples

Python Exception Handling

Python NumPy

Python Pandas

Python File Handling

Python WebSocket

Python GUI Programming

Python Image Processing

Python Miscellaneous

Python Practice

Python Programs

How to scale a NumPy array?

Learn, how can we scale a NumPy array?
By Pranit Sharma Last updated : December 26, 2023

Problem statement

Suppose that we are given a numpy array of shape (n, m) and we need to scale this numpy array by a factor of k which results in an array of shapes (n*k, m*k).

That is, the value of each cell in the original array is copied into k corresponding cells in the resulting array. Assuming arbitrary array size and scaling factor, we need to find the most efficient way to do this.

Scaling a NumPy array

To scale a NumPy array, we can use numpy.kron() which is used to compute the Kronecker product of two arrays which means to create a composite array made of blocks of the second array scaled by the first.

It takes two parameters a, b which are the input arrays for which the Kronecker product is computed.

We can create an array filled with ones of shape K by which we need to scale the original array and then we can apply numpy.kron() on both arrays.

Syntax

Below is the syntax of numpy.kron() method:

numpy.kron(a, b)

Let us understand with the help of an example,

Python code to scale a numpy array

# Import numpy
import numpy as np

# Creating a numpy array
arr = np.array([[1, 1],[0, 1]])

# Display original array
print("Original array:\n",arr,"\n")

# Scaling up the original array
k = 2
res = np.kron(arr,np.ones((k,k)))

# Display result
print("Result:\n",res,"\n")

Output

Example: How to scale a NumPy array?

In this example, we have used the following Python basic topics that you should learn:

Python NumPy Programs »

Advertisement
Advertisement

Comments and Discussions!

Load comments ↻


Advertisement
Advertisement
Advertisement

Copyright © 2025 www.includehelp.com. All rights reserved.