In this tutorial, we will learn how to add column names to a dataframe in Pandas. Column names provide meaningful labels for the data, making it easier to understand and work with the dataframe.
Method 1: Using the columns attribute
One way to add column names is by directly assigning a list of names to the columns
attribute of the dataframe.
Example:
import pandas as pd # Create a dataframe df = pd.DataFrame([[1, 2], [3, 4]], columns=['A', 'B']) # Display the dataframe df.head()
Method 2: Using the rename() function
Another method is to use the rename()
function to assign new column names to the dataframe. This method allows you to specify new names for specific columns or rename all columns at once.
Example:
import pandas as pd # Create a dataframe df = pd.DataFrame([[1, 2], [3, 4]], columns=['C', 'D']) # Rename the columns df = df.rename(columns={'C': 'Column1', 'D': 'Column2'}) # Display the dataframe df.head()
Method 3: Using the set_axis() function
The set_axis()
function can be used to assign new column names to the dataframe. This method allows you to specify the new names as a list.
Example:
import pandas as pd # Create a dataframe df = pd.DataFrame([[1, 2], [3, 4]]) # Assign column names using set_axis() df.set_axis(['Column1', 'Column2'], axis=1, inplace=True) # Display the dataframe df.head()
Method 4: Reading from a CSV file with header
If you are reading data from a CSV file that already contains column names in the header, you can use the header
parameter of the read_csv()
function to automatically assign the column names.
Example:
import pandas as pd # Read data from CSV file with header df = pd.read_csv('data.csv') # Display the dataframe df.head()
Method 5: Using the add_prefix() or add_suffix() functions
The add_prefix()
and add_suffix()
functions can be used to add a prefix or suffix to existing column names, respectively.
Example:
import pandas as pd # Create a dataframe df = pd.DataFrame([[1, 2], [3, 4]], columns=['A', 'B']) # Add a prefix to column names df = df.add_prefix('Prefix_') # Add a suffix to column names df = df.add_suffix('_Suffix') # Display the dataframe df.head()
Method 6: Using the set_columns() function
The set_columns()
function can be used to directly assign a list of column names to the dataframe. This method allows you to replace all existing column names with the new names.
Example:
import pandas as pd # Create a dataframe df = pd.DataFrame([[1, 2], [3, 4]]) # Assign column names using set_columns() df.set_columns(['Column1', 'Column2']) # Display the dataframe df.head()
Last Updated on May 18, 2023 by admin