Pandas DataFrame assign() Method | Create new Columns in DataFrame
Last Updated :
11 Jul, 2024
Python is a great language for data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages, making importing and analyzing data much easier.
The Dataframe.assign() method assigns new columns to a DataFrame, returning a new object (a copy) with the new columns added to the original ones.Â
Existing columns that are re-assigned will be overwritten. The length of the newly assigned column must match the number of rows in the DataFrame.
Example:
Python
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
print("Original Array:", arr)
arr.assign([6, 7, 8, 9, 10])
print("Modified Array:", arr)
Output:
Original Array: [1 2 3 4 5]
Modified Array: [ 6 7 8 9 10]
Syntax
Syntax: DataFrame.assign(**kwargs)Â
Parameters
- kwargs : keywords are the column names. If the values are callable, they are computed on the DataFrame and assigned to the new columns. The callable must not change input DataFrame (though pandas donât check it). If the values are not callable, (e.g. a Series, scalar, or array), they are simply assigned.Â
Returns: A new DataFrame with the new columns in addition to all the existing columns.
For the link to the CSV file Used in the Code, click here
Examples
Let’s look at some Python programs and learn how to use the assign() method of the Pandas library to create new columns in DataFrame with these examples.
Example 1:
Assign a new column called Revised_Salary with a 10% increment of the original Salary.
Python
# importing pandas as pd
import pandas as pd
# Making data frame from the csv file
df = pd.read_csv("nba.csv")
# Printing the first 10 rows of
# the data frame for visualization
df[:10]

Python
# increase the salary by 10 %
df.assign(Revised_Salary = lambda x: df['Salary']
+ df['Salary']/10)
Output:

Assigning more than one column at a time
Python
# importing pandas as pd
import pandas as pd
# Making data frame from the csv file
df = pd.read_csv("nba.csv")
# First column ='New_Team', this column
# will append '_GO' at the end of each team name.
# Second column ='Revised_Salary' will increase
# the salary of all employees by 10 %
df.assign(New_team = lambda x: df['Team']+'_GO',
Revised_Salary = lambda x: df['Salary']
+ df['Salary'] / 10)
Output:

Pandas DataFrame assign() Method | Create new Columns in DataFrame – FAQs
How to Use Regex Replace in Pandas DataFrame
You can use the replace() method in pandas with a regex pattern to replace values in a DataFrame or a Series. This method is very versatile and can handle complex string patterns:
import pandas as pd
# Sample DataFrame
df = pd.DataFrame({
'text': ['foo123', 'bar321', 'baz123']
})
# Replace numbers with 'XYZ' using regex
df['text'] = df['text'].str.replace(r'\d+', 'XYZ', regex=True)
print(df)
How to Replace Values with Regex
To replace values using regex in a DataFrame, specify the regex=True parameter in the replace() method, as shown above. This allows for pattern matching and replacement within strings:
# Replace specific pattern (e.g., anything starting with 'ba')
df['text'] = df['text'].str.replace(r'^ba\w+', 'Matched', regex=True)
print(df)
How to Replace Values in Pandas DataFrame
For non-regex simple replacements, you can use replace() without enabling the regex functionality:
# Replace 'Matched' with 'Found'
df['text'] = df['text'].replace('Matched', 'Found')
print(df)
How to Make a Regex Pattern in Python
Creating a regex pattern in Python involves using raw strings (prefixed with r) to avoid having to escape backslashes. Hereâs how to make a simple regex pattern:
import re
# Regex pattern to match email
pattern = r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b'
# Check if the pattern is valid
try:
re.compile(pattern)
is_valid = True
except re.error:
is_valid = False
print("Is the regex pattern valid?", is_valid)
How to Compare String with Regex in Python
To compare a string against a regex pattern in Python, you can use re.match() or re.search() from the re module:
import re
text = "example@email.com"
match = re.match(pattern, text)
if match:
print("The string matches the pattern.")
else:
print("The string does not match the pattern.")
# Using re.search() to find a pattern anywhere in the string
search_result = re.search(pattern, "User email is example@email.com.")
if search_result:
print("Found a match.")
else:
print("No match found.")
Please Login to comment...