×

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 invert a permutation array in NumPy?

Learn, how can we invert a permutation array in Python NumPy?
By Pranit Sharma Last updated : December 27, 2023

Problem statement

Suppose that we are given a numpy array and we perform some kind of permutation on it, and we need to create an array to represent the inverse of this permutation.

Inverting a permutation NumPy Array

To invert a permutation array in NumPy, we can use numpy.where(p.T) where p is the permutation on the array and T is the transpose of the new array.

Let us understand with the help of an example,

Python code to invert a permutation array in NumPy

# Import numpy
import numpy as np

# Creating a numpy array
arr = np.array([3,2,0,1])
row = np.arange(4)

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

# Permutation
p = np.zeros((4,4),dtype=int)
p[row,arr] = 1

# Inverse of permutation
res = np.where(p.T)[1]

# Display permutation
print("Permutation:\n",p,"\n")

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

Output

Example: How to invert a permutation array in NumPy?

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.