'why pandas.replace inplace = True doesnt work [duplicate]

i have a Data Frame with the following columns

     A   B    C      D
0   1.0 1.0 cob     3.0
1   1.0 1.0 hello   3.0
2   1.0 1.0         3.0
3   1.0 1.0 c       3.0

i am trying to replace the values in column 'D' corresponding to column 'C' having cob and c so i have used replace command like below

df2['D'][(df2['C'].isin(['cob','c']))].replace(3,5)

and the output is fine

0    5.0
3    5.0
Name: D, dtype: float64

but when i use inplace=True option in replace its not working

df2['D'][(df2['C'].isin(['cob','c']))].replace(3,5,inplace=True)
df2['D']

and output is 3 only not 5

0    3.0
1    3.0
2    3.0
3    3.0
Name: D, dtype: float64

can some one help me with this



Solution 1:[1]

If you want to replace any starting value by a specific value:

df.loc[df['C'].isin(['cob', 'c']), 'D'] = 5

if you also want to ensure that the starting value is 3:

df.loc[df['C'].isin(['cob', 'c'])&df['D'].eq(3), 'D'] = 5

output:

     A    B      C    D
0  1.0  1.0    cob  5.0
1  1.0  1.0  hello  3.0
2  1.0  1.0    3.0  NaN
3  1.0  1.0      c  5.0

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1