Articles by FavTutor
  • AI News
  • Data Structures
  • Web Developement
  • AI Code GeneratorNEW
  • Student Help
  • Main Website
No Result
View All Result
FavTutor
  • AI News
  • Data Structures
  • Web Developement
  • AI Code GeneratorNEW
  • Student Help
  • Main Website
No Result
View All Result
Articles by FavTutor
No Result
View All Result
Home Data Science

Pandas DataFrame: Replace Column Values (with code)

Piyush Kaushal by Piyush Kaushal
December 15, 2023
Reading Time: 5 mins read
Pandas DataFrame: Replace Column Values (with code)
Follow us on Google News   Subscribe to our newsletter

Pandas provides a plethora of functions to manipulate and analyze data efficiently, making it a favorite among data scientists and analysts. In this article, we will discuss various methods we can use to replace column values in a DataFrame in Pandas Python.

4 Methods to Replace Column Values in DataFrame

One common task in data preprocessing is replacing values in specific columns. It can be useful for correcting errors, inconsistencies, or inaccuracies in the data. Additionally, the ability to replace values is instrumental in transforming data to meet specific analysis requirements, addressing outliers, and adhering to business rules or guidelines.

Here are 4 unique ways to replace column values in Pandas DataFrame:

1) Using the .replace() Method

The Pandas library provides the .replace() method in Python to replace columns in a DataFrame. The .replace() method is a versatile way to replace values in a Pandas DataFrame. It allows you to specify the column, the value to replace, and the replacement value.

Let us see how it works to replace column values in Pandas DataFrame with an example:

import pandas as pd

data = {'Name': ['Alice', 'Bob', 'Charlie', 'David'],
        'Age': [25, 30, 35, 40],
        'City': ['New York', 'Los Angeles', 'San Francisco', 'Chicago']}

df = pd.DataFrame(data)

# Display the original DataFrame
print('Original DataFrame:\n', df)

# Use the .replace() method
df_copy = df.copy()
df_copy['City'].replace('New York', 'NY', inplace=True)

# Display the updated DataFrame
print('Updated DataFrame:\n', df_copy)

Output:

Original DataFrame:
       Name  Age           City
0    Alice   25       New York
1      Bob   30    Los Angeles
2  Charlie   35  San Francisco
3    David   40        Chicago

Updated DataFrame:
       Name  Age           City
0    Alice   25             NY
1      Bob   30    Los Angeles
2  Charlie   35  San Francisco
3    David   40        Chicago

2) Using the loc() indexer

We can use the loc() indexer method to replace values based on a condition. This allows us to select specific rows and columns of a DataFrame and modify their values.

Let’s check out an example:

import pandas as pd

data = {'Name': ['Alice', 'Bob', 'Charlie', 'David'],
        'Age': [25, 30, 35, 40],
        'City': ['New York', 'Los Angeles', 'San Francisco', 'Chicago']}

df = pd.DataFrame(data)

# Display the original DataFrame
print('Original DataFrame:\n', df)

# Use the .loc() indexer
df_copy = df.copy()
df_copy.loc[df['Age'] > 30, 'Age'] = 30

# Display the updated DataFrame
print('Updated DataFrame:\n', df_copy)

Output:

Original DataFrame:
       Name  Age           City
0    Alice   25       New York
1      Bob   30    Los Angeles
2  Charlie   35  San Francisco
3    David   40        Chicago

Updated DataFrame:
       Name  Age           City
0    Alice   25       New York
1      Bob   30    Los Angeles
2  Charlie   30  San Francisco
3    David   30        Chicago

3) Using Custom Functions with .apply()

We can also use pandas-apply to build custom functions for the replacement of columns in a DataFrame. We can apply a function to each element of a column and replace the values accordingly.

The following example uses apply method to replace column values:

import pandas as pd

data = {'Name': ['Alice', 'Bob', 'Charlie', 'David'],
        'Age': [25, 30, 35, 40],
        'City': ['New York', 'Los Angeles', 'San Francisco', 'Chicago']}

df = pd.DataFrame(data)

# Display the original DataFrame
print('Original DataFrame:\n', df)

# Custom function to replace the columns
state_mapping = {'New York': 'NY', 'Los Angeles': 'CA', 'San Francisco': 'CA', 'Chicago': 'IL'}
def replace_city_with_state(city):
    return state_mapping.get(city, city)

# Use the .apply method
df_copy = df.copy()
df_copy['City'] = df_copy['City'].apply(replace_city_with_state)

# Display the updated DataFrame
print('Updated DataFrame:\n', df_copy)

Output:

Original DataFrame:
       Name  Age           City
0    Alice   25       New York
1      Bob   30    Los Angeles
2  Charlie   35  San Francisco
3    David   40        Chicago

Updated DataFrame:
       Name  Age City
0    Alice   25   NY
1      Bob   30   CA
2  Charlie   35   CA
3    David   40   IL

4) Using the .str.replace()

If you need to replace values within string columns, you can use the .str.replace() method. This method allows you to replace substrings within each element of a string column. This method performs string substitution within each element of the column.

Let us see an example:

import pandas as pd

data = {'Name': ['Alice', 'Bob', 'Charlie', 'David'],
        'Age': [25, 30, 35, 40],
        'City': ['New York', 'Los Angeles', 'San Francisco', 'Chicago']}

df = pd.DataFrame(data)

# Display the original DataFrame
print('Original DataFrame:\n', df)

# Use the .str.replace method
df_copy = df.copy()
df_copy['Name'] = df_copy['Name'].str.replace('Alice', 'Alicia')

# Display the updated DataFrame
print('Updated DataFrame:\n', df_copy)

Output:

Original DataFrame:
       Name  Age           City
0    Alice   25       New York
1      Bob   30    Los Angeles
2  Charlie   35  San Francisco
3    David   40        Chicago

Updated DataFrame:
       Name  Age           City
0   Alicia   25       New York
1      Bob   30    Los Angeles
2  Charlie   35  San Francisco
3    David   40        Chicago

It is always important to handle missing values before replacing columns in Python. You can refer to pandas-fillna to learn how to handle the missing values in a Pandas DataFrame.

Conclusion

In this article, we learned the various methods of replacing a column in a DataFrame of the Pandas library in Python. We explored the replace() method, using apply(), using loc() methods to replace a column in the DataFrame. Replacement of columns is a fairly common application in data analysis. Hence, it is important to master all these methods to perform our tasks more effectively and efficiently.

ShareTweetShareSendSend
Piyush Kaushal

Piyush Kaushal

I am Piyush Kaushal, currently pursuing a degree in software engineering at a prestigious government university. I am dedicated to staying informed about the latest technological developments and continuously expanding my knowledge base. I take great pleasure in sharing my expertise in data science and coding with fellow aspiring minds.

RelatedPosts

Moving Average in Pandas

Calculate Moving Average in Pandas (with code)

January 12, 2024
Pandas Convert Datetime to Date Column

Convert Datetime to Date Column in Pandas (with code)

January 4, 2024
Convert Pandas DataFrame to NumPy Array

Convert Pandas DataFrame to NumPy Array (with code)

January 3, 2024
Pandas DataFrame isna() Method

Pandas DataFrame isna() Method Explained

January 3, 2024
Pandas DataFrame copy() Method

Pandas DataFrame copy() Method Explained

January 1, 2024

About FavTutor

FavTutor is a trusted online tutoring service to connects students with expert tutors to provide guidance on Computer Science subjects like Java, Python, C, C++, SQL, Data Science, Statistics, etc.

Categories

  • AI News, Research & Latest Updates
  • Trending
  • Data Structures
  • Web Developement
  • Data Science

Important Subjects

  • Python Assignment Help
  • C++ Help
  • R Programming Help
  • Java Homework Help
  • Programming Help

Resources

  • About Us
  • Contact Us
  • Editorial Policy
  • Privacy Policy
  • Terms and Conditions

Website listed on Ecomswap. © Copyright 2025 All Rights Reserved.

No Result
View All Result
  • AI News
  • Data Structures
  • Web Developement
  • AI Code Generator
  • Student Help
  • Main Website

Website listed on Ecomswap. © Copyright 2025 All Rights Reserved.