How to use List Comprehension In Python Pandas
Python3
import pandas as pd data = { 'Name' : [ 'Alice' , 'Bob' , 'Charlie' ], 'Age' : [ 25 , 30 , 22 ], 'Salary' : [ 50000 , 60000 , 45000 ]} df = pd.DataFrame(data) # Display original dataset print ( "Original Dataset:" ) print (df) # Rename columns with index numbers using list comprehension df.columns = [f 'Column_{index}' for index in range ( len (df.columns))] # Display dataset with renamed columns print ( "\nDataset with Renamed Columns:" ) print (df) |
Output:
Original Dataset:
Name Age Salary
0 Alice 25 50000
1 Bob 30 60000
2 Charlie 22 45000
Dataset with Renamed Columns:
Column_0 Column_1 Column_2
0 Alice 25 50000
1 Bob 30 60000
2 Charlie 22 45000
In both methods, we first display the original dataset to provide context. The enumerate() function is used to get both the column names and their corresponding index numbers. The new column names are then generated based on these index numbers and applied to the DataFrame.
Rename column name with an index number of the CSV file in Pandas
In this blog post, we will learn how to rename the column name with an index number of the CSV file in Pandas.