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.

jpp
  • 159,742
  • 34
  • 281
  • 339
user3848207
  • 3,737
  • 17
  • 59
  • 104

4 Answers4

24

Using str.replace would work:

df['Grade'] = df['Grade'].str.replace('%', '')
Shaido
  • 27,497
  • 23
  • 70
  • 73
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.

jpp
  • 159,742
  • 34
  • 281
  • 339
  • 2
    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 Aug 10 '18 at 03:53
  • @user3848207, Sure, you can convert to `str` in that case [as per my update]. – jpp Aug 10 '18 at 03:53
5

Why not str.rstrip():

df['Grade'] = df['Grade'].str.rstrip('%')
U13-Forward
  • 69,221
  • 14
  • 89
  • 114
2

So long as we are giving alternatives, can also translate

df.Grade.str.translate(str.maketrans({'%':''})).astype(float) 
rafaelc
  • 57,686
  • 15
  • 58
  • 82
  • What would a practical *difference* be between `translate` and `replace`? – BruceWayne Aug 10 '18 at 04:09
  • 1
    @BruceWayne I believe [this question](https://stackoverflow.com/questions/31143290/python-str-translate-vs-str-replace) has answers more complete than I could post in a comment here ;) – rafaelc Aug 10 '18 at 04:11