# How to swap columns in a numpy array?

Learn, how to swap columns in a numpy array in Python?
Submitted by Pranit Sharma, on January 22, 2023

NumPy is an abbreviated form of Numerical Python. It is used for different types of scientific operations in python. Numpy is a vast library in python which is used for almost every kind of scientific or mathematical operation. It is itself an array which is a collection of various methods and functions for processing the arrays.

## Swapping columns in a numpy array

Suppose that we are given a NumPy array that contains multiple rows and columns, we need to swap two columns with each other.

For this purpose, we have a simple approach of slicing and selecting. We will select our first column by using [: , 0] and the second column by using [: , 1 ] and we will assign their values as the second column and first column respectively.

Let us understand with the help of an example,

## Python code to swap columns in a numpy array

```# Import numpy
import numpy as np

# Creating a numpy array
arr = np.arange(9).reshape(3, 3)

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

# Swapping 1st and second column
arr[:, 0], arr[:, 1] = arr[:, 1], arr[:, 0].copy()

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

Output: What's New (MCQs)

Top Interview Coding Problems/Challenges!

IncludeHelp's Blogs

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates