RSM
RSM

Reputation: 673

conditional replace in pandas dataframe

I have the following dataframe:

df:

A   B                       C
121 The price is $4M        USA
323 The price is $2.2M      USA
454 The price is $62K       Japan
654 The price is $91M(-21%) Japan
877 The price is $432M(91%) USA

I am trying to replace the column B based on the value in column C.

Expected dataframe:

df:

A   B                       C
121 The price is $4M        USA
323 The price is $2.2M      USA
454 The price is Y62K       Japan
654 The price is Y91M(-21%) Japan
877 The price is $432M(91%) USA

How can i do that?

I have tried the following but it doesnt work:

df[(df['C']=='Japan')]['B'].replace(r'\$', "Y")

df[(df['C']=='Japan')]['B'].replace({'$':'Y'}, regex=True)

Upvotes: 0

Views: 376

Answers (3)

rhug123
rhug123

Reputation: 8768

Here is another way.

df.loc[df['C'] == 'Japan','B'] = df['B'].str.replace('$','Y')

Upvotes: 1

Mehdi Golzadeh
Mehdi Golzadeh

Reputation: 2583

Use assign function to do what you are doing right now:

df = df.assign(
    B = lambda x: x.apply(lambda s: x['B'].replace('$', "Y") if x['C'] =='Japan')
)

Upvotes: 1

Henry Yik
Henry Yik

Reputation: 22503

You can use mask:

df["B"] = df["B"].mask(df["C"].eq("Japan"), df["B"].str.replace("$", "Y"))

print (df)

     A                        B      C
0  121         The price is $4M    USA
1  323       The price is $2.2M    USA
2  454        The price is Y62K  Japan
3  654  The price is Y91M(-21%)  Japan
4  877  The price is $432M(91%)    USA

Upvotes: 2

Related Questions