2

I have a dataframe where numbers contained in some cells (in several columns) look like this: '$$10'

I want to replace/remove the '$$'. So far I tried this, but I does not work:

replace_char={'$$':''}

df.replace(replace_char, inplace=True) 
2
  • Can you specify the error you're getting? Commented Oct 17, 2020 at 1:13
  • @ annicheez theres no error, theres simply no effected result. See my answer below. Commented Oct 17, 2020 at 1:18

3 Answers 3

1

An example close to the approach you are taking would be:

df[col_name].str.replace('\$\$', '')

Notice that this has to be done on a series so you have to select the column you would like to apply the replace to.

    amt
0  $$12
1  $$34

df['amt'] = df['amt'].str.replace('\$\$', '')
df

gives:

  amt
0  12
1  34

or you could apply to the full df with:

df.replace({'\$\$':''}, regex=True)
Sign up to request clarification or add additional context in comments.

3 Comments

Awesome. Please mark this as the solution if it worked for you. Good luck.
Hi @B. Bogart. after repalcing the values, the type in the columns where there were replacements is set to object. it there a way to change this while doing the replacement, or it is necessary to add an additional line of code to change dtpes from object to float or int?
You can add .astype('int'). So for example if you are applying to the full df you could do df.replace({'\$\$':''}, regex=True).astype('int')
1

your code is (almost) right. this will work if you had AA:

replace_char={'AA':''}
df.replace(replace_char, inplace=True) 

problem is $$ is a regex and therefore you need to do it differently:

df['your_column'].replace({'\$':''}, regex = True)

example:

df = pd.DataFrame({"A":[1,2,3,4,5,'$$6'],"B":[9,9,'$$70',9,9, np.nan]})


    A   B
0   1   9
1   2   9
2   3   $$70
3   4   9
4   5   9
5   $$6 NaN

do

df['A'].replace({'\$':''}, regex = True)

desired result for columns A:

0    1
1    2
2    3
3    4
4    5
5    6

you can iterate to any column from this point.

Comments

-1

You just need to specify the regex argument. Like:

replace_char={'$$':''}

df.replace(replace_char, in place = True, regex = True) 

'df.replace' should replace it for all entries in the data frame.

1 Comment

Respectfully, this is a collaborative platform. It about solving problems together, not getting the right answer first. In addition, my answer is significantly different from yours. It might be a better solution for the person, which is what we're all aiming for. I did not copy your solution by any means.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.