0

Solved

I have the current dataframe df:

Farmer   Good Fruit
Matt     5
Tom      10

which I want to change to:

Farmer   Fruit
Matt     5
Tom      10

I am wondering if I can convert any column name containing Fruit, such as "Good Fruit" or "Dope Fruit", to simply "Fruit".

By using

df.columns.str.replace('.*Fruit*', 'Fruit', regex=True)

I was able to successfully change the column name to "Fruit". However, I'm not sure how to apply this change to the actual dataframe, df.

Index(['Farmer', 'Fruit'], dtype='object')

edit Thanks to @wjandrea for the solution. The code needs to be changed to:

df.columns = df.columns.str.replace('.*Fruit*', 'Fruit', regex=True)
Michael
  • 1
  • 1

2 Answers2

1

As shown in https://stackoverflow.com/a/16667215/2954547, you can rename columns using an arbitrary function, which is probably the most general solution:

import re

df = df.rename(columns=lambda c: "Fruit" if "Fruit" in c else c)

You can also use the inplace=True option.

shadowtalker
  • 12,529
  • 3
  • 53
  • 96
0

You can achieve this using the rename() function.

df.rename(columns = {'Good Fruit':'Fruit'}, inplace = True)