Disciples
Disciples

Reputation: 703

How to dynamically replace values in pandas.Series?

So I want to conditionally replace values in pandas.DataFrame using mask function, so imagine we have this dataframe:

     Col1           Col2
0    Qeq            10
1    Qeq            20
2    Qwa            30

What I want is to have an ability to replace all values where Col1 == 'Qwa' to f-string referencing OLD value dynamically. So my desired format is: "-{value}" and desired output is:

     Col1           Col2
0    Qeq            10
1    Qeq            20
2    Qwa            -30

Is it possible using .mask function? I've tried following:

# This works but new value in this case is hardcoded
df['Col2'].mask(df['Col1'] == 'Qwa', other='-' + df['Col2'])
# This does not work as it evaluates whole series in a f-string
df['Col2'].mask(df['Col1'] == 'Qwa', other=f'-{df["Col2"]}')

Upvotes: 1

Views: 839

Answers (2)

Quang Hoang
Quang Hoang

Reputation: 150735

How about apply the format function:

df['Col2'].mask(df['Col1'] == 'Qwa', other=df['Col2'].apply('-{}'.format))

Output:

0     10
1     20
2    -30
Name: Col2, dtype: object

Or

df['Col2'].mask(df['Col1'] == 'Qwa', other=df['Col2'].apply('*{}'.format))

Output:

0     10
1     20
2    *30
Name: Col2, dtype: object

Upvotes: 2

Mayank Porwal
Mayank Porwal

Reputation: 34046

Imagine this df:

In [63]: df
Out[63]: 
  Col1  Col2
0  Qeq    10
1  Qeq    20
2  Qwa    30
3  Qwa    40

You can something like, using df.loc:

In [66]: df.loc[df.Col1.eq('Qwa'), 'Col2'] = df.loc[df.Col1.eq('Qwa'), 'Col2'].mul(-1)

In [67]: df
Out[67]: 
  Col1  Col2
0  Qeq    10
1  Qeq    20
2  Qwa   -30
3  Qwa   -40

Upvotes: 1

Related Questions