Pandas replacing values on specific columns

to_rep = dict(zip([1, 3, 2],[3, 6, 7]))
df.replace({'A':to_rep, 'B':to_rep}, inplace = True)

This will return:

   A  B  C
0  3  7  8
1  6  4  8
2  5  3  8

Here is the answer by one of the developers: https://github.com/pydata/pandas/issues/11984

This should ideally show a SettingWithCopyWarning, but I think this is quite difficult to detect.

You should NEVER do this type of chained inplace setting. It is simply bad practice.

idiomatic is:

In [7]: df[['A','B']] = df[['A','B']].replace([1, 3, 2], [3, 6, 7])

In [8]: df
Out[8]: 
   A  B  C
0  3  7  8
1  6  4  8
2  5  3  8

(you can do with df.loc[:,['A','B']] as well, but more clear as above.

Tags:

Python

Pandas