To mass rename columns without name in pandas use the following code:
your_df.rename (columns = ('col_to_be_renamed':'new_name'), inplace=True)
Understanding the use case
Assume that you have acquired some data into your DataFrame from a CSV or Excel file. The data contains columns that are unnamed; which is obviously confusing. You would like to tidy your data by either maintaining the relevant columns, or simply delete the unnecessary ones.
Example data
You can copy the table posted below to follow up with this tutorial. Import the pandas library and use the pd.read_clipboard() method to create a simple DataFrame in your Jupyter or Colab notebook (or any other Python environment you might be using for Data Analysis.
Unnamed: 0 | Interviewer | Interviews | Unnamed: 3 | |
---|---|---|---|---|
0 | 123 | Dave | 11 | 140 |
1 | 111 | Lori | 12 | 140 |
2 | 99 | Moses | 13 | 120 |
As mentioned above, feel free to copy the table then use the following snippet to construct your example HR DataFrame:
import pandas as pd
hr = pd.read_clipboard()
Rename an unnamed column
We will use the DataFrame rename() method and pass a Python mapping dictionary containing one or more columns to be renamed:
hr.rename(columns ={'Unnamed: 0': 'Employee ID'}, inplace = True)
Changing names of multiple columns
In the same fashion we can rename multiple columns:
hr.rename(columns ={'Unnamed: 0': 'Employee ID', 'Unnamed: 3': 'Interview_Count'}, inplace = True)
To find out the updated columns names, use the df.columns attribute.
hr.columns
This will return the column index:
Index(['Employee ID', 'Interviewer', 'Interviews', 'Interview_Count'], dtype='object')
Assign new column names to the DataFrame
An additional possibility, probably less elegant, is to directly assign into the Dataframe column index using a list. For example:
hr.columns = ['Employee ID', 'Interviewer', 'Interviews', 'Interview_Count']
Drop unnamed columns off your DataFrame
If needed, you might want to remove unnamed columns from your DataFrame. Here’s a good tutorial that you might want to follow to accomplish that.