Skip to content
Advertisement

Python Trim Multiple Column Names of a dataframe

I have data frame of 20 columns. All of them have a common text and a serial number. I want to trim the text part and make the name shorter. Below is an example:

JavaScript

Expected output:

JavaScript

Solution1:

JavaScript

Solution2:

JavaScript

Solution1 works fine but I have to prepare an old and new column names list. Instead, I want to iterate through each column name and replace the column text. However, solution2 is not working.

Advertisement

Answer

You could use str.findall on the columns to split into text and number; then use a list comprehension to take only the first letter and join it with the numbers for each column name:

JavaScript

Output:

JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement