Exchange Values of pandas DataFrame in Python (3 Examples)

In this tutorial you’ll learn how to exchange certain cells in a pandas DataFrame in Python programming.

Creation of Example Data

import pandas as pd                                  # Import pandas
my_df = pd.DataFrame({'A':range(10, 15),            # Construct DataFrame in Python
                      'B':range(105, 100, - 1)})
print(my_df)                                        # Display DataFrame in Python
#     A    B
# 0  10  105
# 1  11  104
# 2  12  103
# 3  13  102
# 4  14  101

Example 1: Using Index to Replace Values of pandas DataFrame in Python

my_df.at[1, 'B'] = - 1                              # Modify DataFrame in Python
print(my_df)                                        # Display DataFrame in Python
#     A    B
# 0  10  105
# 1  11   -1
# 2  12  103
# 3  13  102
# 4  14  101

Example 2: Using replace() Function to Replace Values of pandas DataFrame in Python

my_df['A'] = my_df['A'].replace([10, 12, 14], - 2)  # Modify DataFrame in Python
print(my_df)                                        # Display DataFrame in Python
#     A    B
# 0  -2  105
# 1  11   -1
# 2  -2  103
# 3  13  102
# 4  -2  101

Example 3: Using Logical Condition to Replace Values of pandas DataFrame in Python

my_df.loc[my_df.B >= 103, 'B'] = - 3                # Modify DataFrame in Python
print(my_df)                                        # Display DataFrame in Python
#     A    B
# 0  -2   -3
# 1  11   -1
# 2  -2   -3
# 3  13  102
# 4  -2  101

Leave a Reply

Your email address will not be published.

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu
Top