Reputation: 673
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
Reputation: 8768
Here is another way.
df.loc[df['C'] == 'Japan','B'] = df['B'].str.replace('$','Y')
Upvotes: 1
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
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