简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM