×

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

What is correct syntax to swap column values for selected rows in a pandas data frame using just one line?

The correct syntax to swap column values for selected rows in a pandas data frame using just one line. By Pranit Sharma Last updated : October 05, 2023

Pandas is a special tool that allows us to perform complex manipulations of data effectively and efficiently. Inside pandas, we mostly deal with a dataset in the form of DataFrame. DataFrames are 2-dimensional data structures in pandas. DataFrames consist of rows, columns, and data.

Problem statement

Suppose we are given the dataframe with three columns a, b, and, c. Now for a particular column if the value matches a specific value we need to swap the contents of the other two columns.

Swapping column values for selected rows in a pandas data frame using just one line

For this purpose, we will simply assign the swap the values of the other two columns using loc[] property to the original values of the other two columns except using loc[] property also by passing the specific value to match.

Let us understand with the help of an example,

Python program to swap column values for selected rows in a pandas data frame using just one line

# Importing pandas package
import pandas as pd

# Importing numpy package
import numpy as np

# Creating a dictionary
d = {
    'a':  ['left', 'right', 'left', 'right', 'left', 'right'],
    'b': ['right', 'left', 'right', 'left', 'right', 'left'],
    'c': [-1, 1, -1, 1, -1, 1]
}

# Creating a DataFrame
df = pd.DataFrame(d)

# Display DataFrame
print("Original DataFrame:\n",df,"\n")

# Defining the specific values to compare
idx = (df['c'] == 1)

# Swapping values
df.loc[idx,['a','b']] = df.loc[idx,['a','b']].values

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

Output

The output of the above program is:

Example: What is correct syntax to swap column values for selected rows in a pandas data frame using just one line?

Python Pandas Programs »

Advertisement
Advertisement

Comments and Discussions!

Load comments ↻


Advertisement
Advertisement
Advertisement

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