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.

Similar Reads

Renaming Column Name with an Index Number

Pandas, an advanced data manipulation package in Python, includes several methods for working with structured data such as CSV files. You might wish to change the automatically generated column names (0, 1, 2, etc.) to something more illustrative when using Pandas to work with CSV data. Instead of requiring users to refer to confusing default names, Pandas offers a straightforward approach for renaming columns by using the rename() function and providing the index number....

Methods to Rename Column Names

In Pandas, there are primarily two ways to rename columns:...

Pandas Column Name Concepts

Pandas will automatically assign column names (0, 1, 2…) to CSV data when loaded into a DataFrame You can view and work with these default names, but descriptive names are preferable The rename() method allows you to map new names to existing names You refer to columns using their index number (starting from 0)...

Pandas Implementation

Let’s create a simple dataset to demonstrate the renaming process:...

Using rename() function

...

Using List Comprehension

Renaming a Single Column Name with an Index Number...

Conclusion

...

Frequently Asked Questions

...

Contact Us