w3resource

Pandas: Rename all columns with the same pattern of a given DataFrame


68. Rename All Columns with Same Pattern

Write a Pandas program to rename all columns with the same pattern of a given DataFrame.

Sample Solution :

Python Code :

import pandas as pd
df = pd.DataFrame({
    'Name': ['Alberto Franco','Gino Mcneill','Ryan Parkes', 'Eesha Hinton', 'Syed Wharton'],
    'Date_Of_Birth ': ['17/05/2002','16/02/1999','25/09/1998','11/05/2002','15/09/1997'],
    'Age': [18.5, 21.2, 22.5, 22, 23]
})

print("Original DataFrame")
print(df)
df.columns = df.columns.str.lower().str.rstrip()
print("\nRemove trailing (at the end) whitesapce and convert to lowercase of the columns name")
print(df.head())

Sample Output:

Original DataFrame
             Name Date_Of_Birth    Age
0  Alberto Franco     17/05/2002  18.5
1    Gino Mcneill     16/02/1999  21.2
2     Ryan Parkes     25/09/1998  22.5
3    Eesha Hinton     11/05/2002  22.0
4    Syed Wharton     15/09/1997  23.0

Remove trailing (at the end) whitesapce and convert to lowercase of the columns name
             name date_of_birth   age
0  Alberto Franco    17/05/2002  18.5
1    Gino Mcneill    16/02/1999  21.2
2     Ryan Parkes    25/09/1998  22.5
3    Eesha Hinton    11/05/2002  22.0
4    Syed Wharton    15/09/1997  23.0

For more Practice: Solve these Related Problems:

  • Write a Pandas program to rename all columns by converting them to lowercase and removing trailing spaces.
  • Write a Pandas program to apply a regular expression to all column names to remove special characters.
  • Write a Pandas program to prepend a common prefix to all columns and then sort the DataFrame by the new column names.
  • Write a Pandas program to update all column names by replacing underscores with spaces and then output the modified DataFrame.

Python-Pandas Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Pandas program to split a given DataFrame into two random subsets.
Next: Write a Pandas program to merge datasets and check uniqueness.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.