The Wayback Machine - https://web.archive.org/web/20240910220529/https://www.geeksforgeeks.org/pandas-dataframe-assign/
Open In App

Pandas DataFrame assign() Method | Create new Columns in DataFrame

Last Updated : 11 Jul, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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]

dataframe printed

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

Output:

value updated

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:

new column added

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.")


Similar Reads

Create a new column in Pandas DataFrame based on the existing columns
While working with data in Pandas, we perform a vast array of operations on the data to get the data in the desired form. One of these operations could be that we want to create new columns in the DataFrame based on the result of some operations on the existing columns in the DataFrame. Let's discuss several ways in which we can do that. Given a Da
4 min read
Pandas DataFrame hist() Method | Create Histogram in Pandas
A histogram is a graphical representation of the numerical data. Sometimes you'll want to share data insights with someone, and using graphical representations has become the industry standard. Pandas.DataFrame.hist() function plots the histogram of a given Data frame. It is useful in understanding the distribution of numeric variables. This functi
4 min read
Pandas DataFrame transpose() Method: Swap Rows and Columns
Pandas DataFrame is a two-dimensional, size-mutable, potentially heterogeneous tabular data structure with labeled axes (rows and columns). Arithmetic operations align on both row and column labels. It can be thought of as a dictionary-like container for the Series objects. This is the primary data structure of the Pandas. Pandas DataFrame transpos
4 min read
Add New Columns to Polars DataFrame
Polars is a fast DataFrame library implemented in Rust and designed to process large datasets efficiently. It is gaining popularity as an alternative to pandas, especially when working with large datasets or needing higher performance. One common task when working with DataFrames is adding new columns, which can be done easily in Polars. In this ar
3 min read
Pandas DataFrame iterrows() Method | Pandas Method
Pandas DataFrame iterrows() iterates over a Pandas DataFrame rows in the form of (index, series) pair. This function iterates over the data frame column, it will return a tuple with the column name and content in the form of a series. Example: Python Code import pandas as pd df = pd.DataFrame({ 'Name': ['Alice', 'Bob', 'Charlie'], 'Age': [25, 32, 3
2 min read
Pandas DataFrame interpolate() Method | Pandas Method
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 and makes importing and analyzing data much easier.  Python Pandas interpolate() method is used to fill NaN values in the DataFrame or Series using various interpolation techniques to fill the m
3 min read
Pandas DataFrame duplicated() Method | Pandas Method
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas duplicated() method identifies duplicated rows in a DataFrame. It returns a boolean series which is True only for unique rows. Ex
3 min read
Difference of two columns in Pandas dataframe
Difference of two columns in pandas dataframe in Python is carried out by using following methods : Method #1 : Using ” -” operator. import pandas as pd # Create a DataFrame df1 = { 'Name':['George','Andrea','micheal', 'maggie','Ravi','Xien','Jalpa'], 'score1':[62,47,55,74,32,77,86], 'score2':[45,78,44,89,66,49,72]} df1 = pd.DataFrame(df1,columns=
2 min read
Split a text column into two columns in Pandas DataFrame
Let's see how to split a text column into two columns in Pandas DataFrame. Method #1 : Using Series.str.split() functions. Split Name column into two different columns. By default splitting is done on the basis of single space by str.split() function. # import Pandas as pd import pandas as pd # create a new data frame df = pd.DataFrame({'Name': ['J
3 min read
Getting frequency counts of a columns in Pandas DataFrame
Given a Pandas dataframe, we need to find the frequency counts of each item in one or more columns of this dataframe. This can be achieved in multiple ways: Method #1: Using Series.value_counts() This method is applicable to pandas.Series object. Since each DataFrame object is a collection of Series object, we can apply this method to get the frequ
2 min read
Show all columns of Pandas DataFrame in Jupyter Notebook
In this article, we will discuss how to show all the columns of a Pandas DataFrame in a Jupyter notebook using Python. Show All Columns and Rows in a Pandas DataFrame Pandas have a very handy method called the get.option(), by this method, we can customize the output screen and work without any inconvenient form of output. Pandas set_option() is us
3 min read
Conditional operation on Pandas DataFrame columns
Suppose you have an online store. The price of the products is updated frequently. While calculating the final price on the product, you check if the updated price is available or not. If not available then you use the last price available. Solution #1: We can use conditional expression to check if the column is present or not. If it is not present
4 min read
How to widen output display to see more columns in Pandas dataframe?
In Python, if there are many more number of columns in the dataframe, then not all the columns will be shown in the output display. So, let's see how to widen output display to see more columns. Method 1: Using pandas.set_option() function. This function is used to set the value of a specified option. Syntax: pandas.set_option(pat, value) Returns:
2 min read
Drop rows from Pandas dataframe with missing values or NaN in columns
Pandas provides various data structures and operations for manipulating numerical data and time series. However, there can be cases where some data might be missing. In Pandas missing data is represented by two value: None: None is a Python singleton object that is often used for missing data in Python code. NaN: NaN (an acronym for Not a Number),
4 min read
Get the number of rows and number of columns in Pandas Dataframe
Pandas provide data analysts a variety of pre-defined functions to Get the number of rows and columns in a data frame. In this article, we will learn about the syntax and implementation of few such functions. Method 1: Using df.axes() Method axes() method in pandas allows to get the number of rows and columns in a go. It accepts the argument '0' fo
3 min read
Apply a function to single or selected columns or rows in Pandas Dataframe
In this article, we will learn different ways to apply a function to single or selected columns or rows in Dataframe. We will use Dataframe/series.apply() method to apply a function. Apply a function to single row in Pandas DataframeHere, we will use different methods to apply a function to single rows by using Pandas dataframe. First lets create a
5 min read
Sort rows or columns in Pandas Dataframe based on values
In this article, Let's discuss how to Sort rows or columns in Pandas Dataframe based on values. Pandas sort_values() method sorts a data frame in Ascending or Descending order of passed Column. It's different than the sorted Python function since it cannot sort a data frame and particular column cannot be selected. Syntax: DataFrame.sort_values(by,
7 min read
Get minimum values in rows or columns with their index position in Pandas-Dataframe
Let’s discuss how to find minimum values in rows & columns of a Dataframe and also their index position. a) Find the minimum value among rows and columns : Dataframe.min() : This function returns the minimum of the values in the given object. If the input is a series, the method will return a scalar which will be the minimum of the values in the se
4 min read
Concatenate two columns of Pandas dataframe
Let's discuss how to Concatenate two columns of dataframe in pandas python. We can do this by using the following functions : concat() append() join() Example 1 : Using the concat() method. # importing the module import pandas as pd # creating 2 DataFrames location = pd.DataFrame({'area': ['new-york', 'columbo', 'mumbai']}) food = pd.DataFrame({'fo
1 min read
Count the number of rows and columns of a Pandas dataframe
Pandas allow us to get the shape of the Dataframe by counting the number of rows and columns in the Dataframe. You can try various approaches to learn to count the number of rows and columns in a Pandas. Example: Input: {'name': ['Katherine', 'James', 'Emily', 'Michael', 'Matthew', 'Laura'], 'score': [98, 80, 60, 85, 49, 92], 'age': [20, 25, 22, 24
4 min read
Count the number of rows and columns of Pandas dataframe
In this article, we'll see how we can get the count of the total number of rows and columns in a Pandas DataFrame. There are different methods by which we can do this. Let's see all these methods with the help of examples. Example 1: We can use the dataframe.shape to get the count of rows and columns. dataframe.shape[0] and dataframe.shape[1] gives
2 min read
Count the NaN values in one or more columns in Pandas DataFrame
Let us see how to count the total number of NaN values in one or more columns in a Pandas DataFrame. In order to count the NaN values in the DataFrame, we are required to assign a dictionary to the DataFrame and that dictionary should contain numpy.nan values which is a NaN(null) value. Consider the following DataFrame. # importing the modules impo
2 min read
Get the datatypes of columns of a Pandas DataFrame
Let us see how to get the datatypes of columns in a Pandas DataFrame. TO get the datatypes, we will be using the dtype() and the type() function.Example 1 : C/C++ Code # importing the module import pandas as pd # creating a DataFrame dictionary = {'Names':['Simon', 'Josh', 'Amen', 'Habby', 'Jonathan', 'Nick', 'Jake'], 'Countries':['AUSTRIA', 'BELGI
2 min read
Highlight Pandas DataFrame's specific columns using applymap()
Let us see how to highlight elements and specific columns of a Pandas DataFrame. We can do this using the applymap() function of the Styler class. Styler.applymap() Syntax : Styler.applymap(self, func, subset = None, **kwargs) Parameters : func : takes a scalar and returns a scalar. subset : valid indexer to limit data to before applying the functi
2 min read
Highlight Pandas DataFrame's specific columns using apply()
Let us see how to highlight specific columns of a Pandas DataFrame. We can do this using the apply() function of the Styler class. Styler.apply() Syntax : Styler.apply(func, axis = 0, subset = None, **kwargs) Parameters : func : function should take a Series or DataFrame (depending on-axis), and return an object with the same shape. Must return a D
2 min read
Select all columns, except one given column in a Pandas DataFrame
DataFrame Data structure are the heart of Pandas library. DataFrames are basically two dimension Series object. They have rows and columns with rows representing the index and columns representing the content. Now, let's see how to Select all columns, except one given column in Pandas DataFrame in Python. Creating a DataFrame: C/C++ Code # import p
2 min read
Sort the Pandas DataFrame by two or more columns
In this article, our basic task is to sort the data frame based on two or more columns. For this, Dataframe.sort_values() method is used. This method sorts the data frame in Ascending or Descending order according to the columns passed inside the function. First, Let's Create a Dataframe: C/C++ Code #import python library import pandas as pd # dict
2 min read
Count number of columns of a Pandas DataFrame
Let's discuss how to count the number of columns of a Pandas DataFrame. Lets first make a dataframe. Example: C/C++ Code # Import Required Libraries import pandas as pd import numpy as np # Create a dictionary for the dataframe dict = {'Name': ['Sukritin', 'Sumit Tyagi', 'Akriti Goel', 'Sanskriti', 'Abhishek Jain'], 'Age': [22, 20, np.inf, -np.inf,
2 min read
Add multiple columns to dataframe in Pandas
In Pandas, we have the freedom to add columns in the data frame whenever needed. There are multiple ways to add columns to pandas dataframe. Add multiple columns to a DataFrame using Lists C/C++ Code # importing pandas library import pandas as pd # creating and initializing a nested list students = [['jackma', 34, 'Sydeny', 'Australia'], ['Ritika',
3 min read
How to display bar charts in Pandas dataframe on specified columns?
In this article we will see how to display bar charts in dataframe on specified columns. For doing this task we are using DataFrame.style.bar() method of Pandas Dataframe. Syntax: pandas.DataFrame.style.bar(columns_list, color) Return: Dataframe with the given color bar strips on the positive definite values. The None value and the negative values
1 min read