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 »

Comments and Discussions!

Load comments ↻





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