user6053895
user6053895

Reputation:

Renaming column name based on its value Pandas

I have the following data frame.

df 

col_1    col_2     col_3
min1     max1     target1
min2     max2     target2

I would like to rename columns col_1, col_2, col_3 based on their value as Min, Max, and Target respectively. I would like to have something below as a result.

Min     Max     Target
min1    max1    target1
min2    max2    target2

Can anyone show me a simple trick to do this using Pandas python?

Upvotes: 0

Views: 104

Answers (1)

above_c_level
above_c_level

Reputation: 3929

Well, I am not sure that you should rename columns this way, but here is a way you could do it. First remove numbers from string and then use the most common string.

from collections import Counter

cols = [Counter(df[col].str.replace('\d+', '')).most_common()[0][0].capitalize()
        for col in df.columns
        ]

df.columns = cols

Output:

    Min     Max     Target
0   min1    max1    target1
1   min2    max2    target2

Upvotes: 2

Related Questions