The Wayback Machine - https://web.archive.org/web/20240909182633/https://www.geeksforgeeks.org/add-column-names-to-dataframe-in-pandas/
Open In App

Add column names to dataframe in Pandas

Last Updated : 24 Nov, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In this article, we are going to see how to add column names to a dataframe. Let us how to add names to DataFrame columns in Pandas.

Add Column Names to Pandas Dataframe

Below are the steps and methods by which we can add column names in the Pandas dataframe in Python:

Creating the DataFrame

Let’s first create an example DataFrame for demonstration reasons before moving on to adding column names. There are several ways in Pandas to add column names to your DataFrame:

python3




# importing the pandas library
import pandas as pd
 
# creating lists
l1 =["Amar", "Barsha", "Carlos", "Tanmay", "Misbah"]
l2 =["Alpha", "Bravo", "Charlie", "Tango", "Mike"]
l3 =[23, 25, 22, 27, 29]
l4 =[69, 54, 73, 70, 74]
 
# creating the DataFrame
team = pd.DataFrame(list(zip(l1, l2, l3, l4)))
 
# displaying the DataFrame
print(team)


Output

0        1   2   3
0 Amar Alpha 23 69
1 Barsha Bravo 25 54
2 Carlos Charlie 22 73
3 Tanmay Tango 27 70
4 Misbah Mike 29 74

Here we can see that the columns in the DataFrame are unnamed.

Adding column name to the DataFrame

We can add columns to an existing DataFrame using its columns attribute.

python3




# adding column name to the respective columns
team.columns =['Name', 'Code', 'Age', 'Weight']
 
# displaying the DataFrame
print(team)


 Output

 Name     Code  Age  Weight
0 Amar Alpha 23 69
1 Barsha Bravo 25 54
2 Carlos Charlie 22 73
3 Tanmay Tango 27 70
4 Misbah Mike 29 74

Now the DataFrame has column names.

Adding Column Name using dataframe()

We can add column name by using giving a parameter inside the dataframe() function.

Python3




column_name = ['Name', 'Code', 'Age', 'Weight']
team = pd.DataFrame(list(zip(l1, l2, l3, l4)), columns=column_name)
print(team)


Output

 Name     Code  Age  Weight 
0 Amar Alpha 23 69
1 Barsha Bravo 25 54
2 Carlos Charlie 22 73
3 Tanmay Tango 27 70
4 Misbah Mike 29 74

Renaming Column Name of a DataFrame

We can rename the columns of a DataFrame by using the rename() function.

python3




# reanming the DataFrame columns
team.rename(columns = {'Code':'Code-Name',
                       'Weight':'Weight in kgs'},
            inplace = True)
 
# displaying the DataFrame
print(team)


Output

Name Code-Name  Age  Weight in kgs
0 Amar Alpha 23 69
1 Barsha Bravo 25 54
2 Carlos Charlie 22 73
3 Tanmay Tango 27 70
4 Misbah Mike 29 74

We can see the names of the columns have been changed.



Similar Reads

Change column names and row indexes in Pandas DataFrame
Given a Pandas DataFrame, let's see how to change its column names and row indexes. About Pandas DataFramePandas DataFrame are rectangular grids which are used to store data. It is easy to visualize and work with data when stored in dataFrame. It consists of rows and columns.Each row is a measurement of some instance while column is a vector which
4 min read
How to Sort a Pandas DataFrame based on column names or row index?
Pandas dataframe.sort_index() method sorts objects by labels along the given axis. Basically, the sorting algorithm is applied to the axis labels rather than the actual data in the Dataframe and based on that the data is rearranged. Creating Pandas Dataframe Create a DataFrame object from the Python list of tuples with columns and indices, say colu
3 min read
Get column index from column name of a given Pandas DataFrame
In this article we will see how to get column index from column name of a Dataframe. We will use Dataframe.columns attribute and Index.get_loc method of pandas module together. Syntax: DataFrame.columns Return: column names index Syntax: Index.get_loc(key, method=None, tolerance=None) Return: loc : int if unique index, slice if monotonic index, els
2 min read
Create a Pandas DataFrame from a Numpy array and specify the index column and column headers
This article demonstrates multiple examples to convert the Numpy arrays into Pandas Dataframe and to specify the index column and column headers for the data frame. Example 1: In this example, the Pandas dataframe will be generated and proper names of index column and column headers are mentioned in the function. This approach can be used when ther
4 min read
Convert given Pandas series into a dataframe with its index as another column on the dataframe
First of all, let we understand that what are pandas series. Pandas Series are the type of array data structure. It is one dimensional data structure. It is capable of holding data of any type such as string, integer, float etc. A Series can be created using Series constructor. Syntax: pandas.Series(data, index, dtype, copy) Return: Series object.
1 min read
How to get column and row names in DataFrame?
While analyzing the real datasets which are often very huge in size, we might need to get the rows or index names and columns names in order to perform certain operations. Note: For downloading the nba dataset used in the below examples Click Here Getting row names in Pandas dataframe First, let's create a simple dataframe with nba.csv C/C++ Code #
3 min read
How to add Empty Column to Dataframe in Pandas?
In DataFrames, Empty columns are defined and represented with NaN Value(Not a Number value or undefined or unrepresentable value). There are various methods to add Empty Column to Pandas Dataframe in Python. Method 1: Add Empty Column to Dataframe using the Assignment Operator We are using the assignment operator to assign empty strings to two newl
3 min read
Add Column to Pandas DataFrame with a Default Value
The three ways to add a column to Pandas DataFrame with Default Value. Using pandas.DataFrame.assign(**kwargs)Using [] operatorUsing pandas.DataFrame.insert()Using Pandas.DataFrame.assign(**kwargs) It Assigns new columns to a DataFrame and returns a new object with all existing columns to new ones. Existing columns that are re-assigned will be over
2 min read
Add column with constant value to pandas dataframe
Prerequisite: Pandas In this article, we will learn how to add a new column with constant value to a Pandas DataFrame. Before that one must be familiar with the following concepts: Pandas DataFrame : Pandas DataFrame is two-dimensional size-mutable, potentially heterogeneous tabular arrangement with labeled axes (rows and columns). A Data frame may
2 min read
How to add column from another DataFrame in Pandas ?
In this discussion, we will explore the process of adding a column from another data frame in Pandas. Pandas is a powerful data manipulation library for Python, offering versatile tools for handling and analyzing structured data. Add column from another DataFrame in Pandas There are various ways to add a column from another DataFrame in Pandas. Her
6 min read
Remove spaces from column names in Pandas
Removing spaces from column names in pandas is not very hard we easily remove spaces from column names in pandas using replace() function. We can also replace space with another character. Let's see the example of both one by one. Example 1: remove the space from column name Python Code # import pandas import pandas as pd # create data frame Data =
1 min read
Pandas - Remove special characters from column names
Let us see how to remove special characters like #, @, &, etc. from column names in the pandas data frame. Here we will use replace function for removing special character. Example 1: remove a special character from column names Python Code # import pandas import pandas as pd # create data frame Data = {'Name#': ['Mukul', 'Rohan', 'Mayank', 'Sh
1 min read
How to Get Column Names in Pandas
While analyzing the real datasets which are often very huge in size, we might need to get the pandas column names in order to perform some certain operations. Let's discuss how to get column names in the Pandas . Syntax to Get Column Names in Pandas # Get column names as an Index objectcolumn_names = df.columns Get Column Names in Pandas Get a list
3 min read
How to get rows/index names in Pandas dataframe
While analyzing the real datasets which are often very huge in size, we might need to get the rows or index names in order to perform some certain operations. Let's discuss how to get row names in Pandas dataframe. First, let's create a simple dataframe with nba.csv C/C++ Code # Import pandas package import pandas as pd # making data frame data = p
2 min read
Create a DataFrame from a Numpy array and specify the index column and column headers
Let us see how to create a DataFrame from a Numpy array. We will also learn how to specify the index and the column headers of the DataFrame. Approach : Import the Pandas and Numpy modules. Create a Numpy array. Create list of index values and column values for the DataFrame. Create the DataFrame. Display the DataFrame. Example 1 : # importiong the
2 min read
Capitalize first letter of a column in Pandas dataframe
Analyzing real-world data is somewhat difficult because we need to take various things into consideration. Apart from getting the useful data from large datasets, keeping data in required format is also very important. One might encounter a situation where we need to capitalize any specific column in given dataframe. Let's see how can we capitalize
2 min read
Apply uppercase to a column in Pandas dataframe
Analyzing a real world data is some what difficult because we need to take various things into consideration. Apart from getting the useful data from large datasets, keeping data in required format is also very important. One might encounter a situation where we need to uppercase each letter in any specific column in given dataframe. Let's see how
2 min read
How to lowercase strings in a column in Pandas dataframe
Analyzing real-world data is somewhat difficult because we need to take various things into consideration. Apart from getting the useful data from large datasets, keeping data in required format is also very important. One might encounter a situation where we need to lowercase each letter in any specific column in given dataframe. Let's see how to
2 min read
Get n-smallest values from a particular column in Pandas DataFrame
Pandas DataFrame is two-dimensional size-mutable, potentially heterogeneous tabular data structure with labeled axes (rows and columns). Let's see how can we can get n-smallest values from a particular column in Pandas DataFrame. Observe this dataset first. We'll use 'Age', 'Weight' and 'Salary' columns of this data in order to get n-smallest value
1 min read
Get n-largest values from a particular column in Pandas DataFrame
Pandas DataFrame is two-dimensional size-mutable, potentially heterogeneous tabular data structure with labeled axes (rows and columns). Let's see how can we can get n-largest values from a particular column in Pandas DataFrame. Observe this dataset first. We’ll use ‘Age’, ‘Weight’ and ‘Salary’ columns of this data in order to get n-largest values
1 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
Create a column using for loop in Pandas Dataframe
Adding a new column in an already created dataframe is quite easy. Adding a new column is actually required to process the data of dataframe created earlier. For that purpose, we can process the existing data and make a separate column to store the data. The simplest way to add a new column along with data is by creating a new column and assigning
3 min read
Getting Unique values from a column in Pandas dataframe
Let's see how can we retrieve the unique values from pandas dataframe. Let's create a dataframe from CSV file. We are using the past data of GDP from different countries. You can get the dataset from here. # import pandas as pd import pandas as pd gapminder_csv_url ='http://bit.ly/2cLzoxH' # load the data with pd.read_csv record = pd.read_csv(gapmi
2 min read
Split a column in Pandas dataframe and get part of it
When a part of any column in Dataframe is important and the need is to take it separate, we can split a column on the basis of the requirement. We can use Pandas .str accessor, it does fast vectorized string operations for Series and Dataframes and returns a string object. Pandas str accessor has number of useful methods and one of them is str.spli
2 min read
Return the Index label if some condition is satisfied over a column in Pandas Dataframe
Given a Dataframe, return all those index labels for which some condition is satisfied over a specific column. Solution #1: We can use simple indexing operation to select all those values in the column which satisfies the given condition. C/C++ Code # importing pandas as pd import pandas as pd # Create the dataframe df = pd.DataFrame({'Date':['10/2
2 min read
Check if a column starts with given string in Pandas DataFrame?
In this program, we are trying to check whether the specified column in the given data frame starts with specified string or not. Let us try to understand this using an example suppose we have a dataset named student_id, date_of_joining, branch. Example: C/C++ Code #importing library pandas as pd import pandas as pd #creating data frame for student
2 min read
How to Convert Dataframe column into an index in Python-Pandas?
Pandas provide a convenient way to handle data and its transformation. Let's see how can we convert a data frame column to row name or index in Pandas. Create a dataframe first with dict of lists. C/C++ Code # importing pandas as pd import pandas as pd # Creating a dict of lists data = {'Name':["Akash", "Geeku", "Pankaj
2 min read
How to Convert Index to Column in Pandas Dataframe?
Pandas is a powerful tool which is used for data analysis and is built on top of the python library. The Pandas library enables users to create and manipulate dataframes (Tables of data) and time series effectively and efficiently. These dataframes can be used for training and testing machine learning models and Analyzing data. Converting Index to
2 min read
How to Concatenate Column Values in Pandas DataFrame?
Many times we need to combine values in different columns into a single column. There can be many use cases of this, like combining first and last names of people in a list, combining day, month, and year into a single column of Date, etc. Now we'll see how we can achieve this with the help of some examples. Example 1: In this example, we'll combin
2 min read
Check whether a given column is present in a Pandas DataFrame or not
Consider a Dataframe with 4 columns : 'ConsumerId', 'CarName', CompanyName, and 'Price'. We have to determine whether a particular column is present in the DataFrame or not in Pandas Dataframe using Python. Creating a Dataframe to check if a column exists in Dataframe C/C++ Code # import pandas library import pandas as pd # dictionary d = {'Consume
2 min read