Home > Software design >  Replace value in column B using dictionary if column A is equal to specific value
Replace value in column B using dictionary if column A is equal to specific value

Time:07-16

This is my dataset:

        pos    result
     0   1       AA
     1   1       AB
     2   1       BB
     3   2       CC
     4   2       CA
     5   2       AC
     6   3       AA
     7   3       DD
     8   3       CC
     9   4       DD
    10   4       AB
    11   4       BA

At the moment, I replace values in a column with this code:

replaceValues = {
    'AA': 'A',
    'BB': 'B',
    'CC': 'C',
    'DD': 'D'
}

df[ 'result' ].replace( to_replace=replaceValues, inplace=True )

and it works great.

But I would like to do the same, but only where column 'pos' are equal to '2' or '3' to get this desired result:

        pos    result
     0   1       AA
     1   1       AB
     2   1       BB
     3   2       C
     4   2       CA
     5   2       AC
     6   3       A
     7   3       D
     8   3       CC
     9   4       DD
    10   4       AB
    11   4       BA

CodePudding user response:

You can first create replace values then use pandas.mask and only set values for those rows that have pos==2 or pos==3.

rep = df['result'].replace(replaceValues)
df['result'] = df['result'].mask(df['pos'].isin([2,3]), rep)
print(df)

    pos result
0     1     AA
1     1     AB
2     1     BB
3     2      C
4     2     CA
5     2     AC
6     3      A
7     3      D
8     3      C
9     4     DD
10    4     AB
11    4     BA

CodePudding user response:

You can use the .loc to filter your results like this:

df['result'].loc[(df['pos'] == 2) | (df['pos'] == 3)].replace(replaceValues)
  • Related