How can I make my .replace function more efficient rather than calling the same .rename function multiple times?

Viewed 51

All I want to do is rename the values in my dataframe. This code works but I'd like to figure out how to condense all this line of code to maybe just 1 line instead.

I'm using the fmri sample set from the seaborn library.

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

fmri = sns.load_dataset('fmri')
fmri.columns = ['Subject','Timepoint','Event','Region','Signal']
fmri=fmri.set_index('Subject') 

fmri = fmri.replace(['frontal'],'Frontal')
fmri = fmri.replace(['parietal'],'Parietal')
fmri = fmri.replace(['cue'],'Cue')
fmri = fmri.replace(['stim'],'Stim')

print(fmri)
2 Answers

If you want a more generalized/elaborated replacement, bear in mind DataFrame.replace also takes a dict as a parameter:

fmri.replace({'frontal': 'Frontal', 'parietal': 'Parietal', 'cue': 'Cue', 'stim': 'Stim'}, inplace=True)

str.title

generalized for all strings in the two columns ['Event', 'Region']

fmri.assign(**fmri[['Event', 'Region']].applymap(str.title))

         Timepoint Event    Region    Signal
Subject                                     
s13             18  Stim  Parietal -0.017552
s5              14  Stim  Parietal -0.080883
s12             18  Stim  Parietal -0.081033
s11             18  Stim  Parietal -0.046134
s10             18  Stim  Parietal -0.037970
...            ...   ...       ...       ...
s0               8   Cue   Frontal  0.018165
s13              7   Cue   Frontal -0.029130
s12              7   Cue   Frontal -0.004939
s11              7   Cue   Frontal -0.025367
s0               0   Cue  Parietal -0.006899

[1064 rows x 4 columns]
Related