1

I want to rename the elements in my pandas dataframe column named Casa Code.

I can do it the following way, see below, but it requires stating Casa Code as index.

How can I do a simple renaming of the elements in Casa Code without having to state a column as index beforehand?

#Rename Casa Code
df = df.set_index('Casa Code')
df = df.rename(index={'TT01':'1100',
                      'CP01':'1101',
                      'CP02':'1102',
                              })
StatsScared
  • 517
  • 6
  • 20
  • What does rename the elements of a column mean? Elements don't have names. – Denziloe Aug 27 '18 at 16:10
  • 2
    Don't set the index. Do `df['Casa Code'] = df['Casa Code'].map({'TT01':'1100', 'CP01':'1101', 'CP02':'1102', })` – cs95 Aug 27 '18 at 16:13
  • @Denziloe, I have a column called `Casa Code` it has three rows containing the following three values: TT01, CP01, CP02. I would like to rename the three values to: 1100, 1101, 1102. Sorry if I used incorrect terminology. – StatsScared Aug 27 '18 at 16:13
  • Possible duplicate of [Remap values in pandas column with a dict](https://stackoverflow.com/questions/20250771/remap-values-in-pandas-column-with-a-dict) – ALollz Aug 27 '18 at 16:15
  • No problem, the correct terminology is simply "map" or even just "change". You're changing the actual thing, not its name. As @ALollz says, the `map` method can do this. – Denziloe Aug 27 '18 at 16:15
  • Thanks, @coldspeed. `map` worked. However, why would one prefer `map` over `replace` in this case? Both seem to work. – StatsScared Aug 27 '18 at 18:04
  • Map is tons faster than replace. – cs95 Aug 27 '18 at 18:44
  • I forgot to add. One downside of `map` (versus `replace`) that I found, is that it only works if I want to replace _all_ values in my column of interest. If not, then it will replace those values with my desired values and all others with NaN. – StatsScared Aug 27 '18 at 18:46

0 Answers0