user3848207
user3848207

Reputation: 4907

Remove certain string from entire column in pandas dataframe

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.

Upvotes: 18

Views: 52455

Answers (4)

jpp
jpp

Reputation: 164623

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.

Upvotes: 7

rafaelc
rafaelc

Reputation: 59274

So long as we are giving alternatives, can also translate

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

Upvotes: 2

U13-Forward
U13-Forward

Reputation: 71560

Why not str.rstrip():

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

Upvotes: 5

Shaido
Shaido

Reputation: 28321

Using str.replace would work:

df['Grade'] = df['Grade'].str.replace('%', '')

Upvotes: 24

Related Questions