baxx
baxx

Reputation: 4725

Conditionally replace values in a subset of a pandas dataframe

Given the following data:

dt = pd.DataFrame({"file": ["a", "a", "b", "b"], "val": [0, 1, 1, 2]})

which looks as

  file  val
0    a    0
1    a    1
2    b    1
3    b    2

I would like to repace 0 with 2 where file == 'a'.

The final result being:

  file  val
0    a    2
1    a    1
2    b    1
3    b    2

Upvotes: 0

Views: 44

Answers (1)

BENY
BENY

Reputation: 323346

Let us try

dt.loc[dt.file.eq('a')&dt.val.eq(0),'val']=2
dt
  file  val
0    a    2
1    a    1
2    b    1
3    b    2

Upvotes: 3

Related Questions