0

I was seeking a pandas solution to the following problem

Dataframe

col1,col2
1,a
2,a
3,a
4,a

Desired output: Replace every instance of a in col2 with a different value

col1,col2
1,cat
2,elephant
3,monkey
4,tiger

I've tried the replace() function, but that replace all occurrences of a

df = df['col2'].replace('a','cat')

But doing this results in

col1,col2
1,cat
2,cat
3,cat
4,cat
rs79
  • 2,311
  • 2
  • 33
  • 39

2 Answers2

1

You need to create the addtional key with cumcount

df['new'] = df.groupby('col2').cumcount().add(1).astype(str).add(df.col2)
df['new'].replace({'1a':'cat'})
Out[375]: 
0    cat
1     2a
2     3a
3     4a
dtype: object
BENY
  • 317,841
  • 20
  • 164
  • 234
1

This should do it:

replacing_values = ["cat", "elephant", "monkey", "tiger"]
a_indices = (df["col2"] == "a").index
df.loc[a_indices, "col2"] = replacing_values
Mustafa Aydın
  • 17,645
  • 4
  • 15
  • 38