4

How come when i want to replace a value I have to use this block of code:

data['Organization'].str.replace('Greece','Rome')

why cant I use this:

data['Organization'].replace('Greece','Rome').

I've seen others use method two before without passing a string method. My question is can i pass a series method using replace function and what is the line of code?

cs95
  • 379,657
  • 97
  • 704
  • 746
grim_reaper
  • 43
  • 1
  • 1
  • 8

2 Answers2

7

pd.Series.replace is different to pd.Series.str.replace:

Here's a minimal example demonstrating the difference:

df = pd.DataFrame({'A': ['foo', 'fuz', np.nan]})

df['B'] = df['A'].replace(['foo', 'fuz'], ['food', 'fuzzy'])
df['C'] = df['A'].str.replace('f.', 'ba', regex=True)

print(df)

     A      B    C
0  foo   food  bao
1  fuz  fuzzy  baz
2  NaN    NaN  NaN
jpp
  • 159,742
  • 34
  • 281
  • 339
1

str.replace by default does a regex based replacement which also works with partial matches. replace, OTOH, will only perform replacements based on full matches by default unless the regex flag is set to true.

data['Organization'] = (
    data['Organization'].replace({'Greece': 'Rome'}, regex=True))
cs95
  • 379,657
  • 97
  • 704
  • 746