18

I have a pandas dataframe df with the contents below:

  Date          Factor       Expiry         Grade  
0 12/31/1991    2.138766     3/30/1992      -3.33% 
1 10/29/1992    2.031381     2/8/1993       -1.06% 
2 5/20/1993     2.075670     6/4/1993       -6.38% 

I would like the remove the % character from all the rows in the Grade column. The result should look like this:

  Date          Factor     Expiry        Grade  
0 12/31/1991    2.138766   3/30/1992     -3.33 
1 10/29/1992    2.031381   2/8/1993      -1.06 
2 5/20/1993     2.075670   6/4/1993      -6.38 

I am using Python v3.6.

4 Answers 4

24

Using str.replace would work:

df['Grade'] = df['Grade'].str.replace('%', '')
Sign up to request clarification or add additional context in comments.

Comments

7

You can use string slicing and then convert to a numeric type via pd.to_numeric:

df['Grade'] = pd.to_numeric(df['Grade'].astype(str).str[:-1], errors='coerce')

Conversion to float is recommended as a series of strings will be held in a generic and inefficient object dtype, while numeric types permit vectorised operations.

2 Comments

Thanks for the answer. Upvoted because I like the idea of converting to float. When I use your answer, I get the error AttributeError: Can only use .str accessor with string values, which use np.object_ dtype in pandas. I have no problem when I use df['Grade'] = df['Grade'].str.replace('%', '').
@user3848207, Sure, you can convert to str in that case [as per my update].
5

Why not str.rstrip():

df['Grade'] = df['Grade'].str.rstrip('%')

Comments

2

So long as we are giving alternatives, can also translate

df.Grade.str.translate(str.maketrans({'%':''})).astype(float) 

2 Comments

What would a practical difference be between translate and replace?
@BruceWayne I believe this question has answers more complete than I could post in a comment here ;)

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.