Reputation: 4907
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
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
Reputation: 59274
So long as we are giving alternatives, can also translate
df.Grade.str.translate(str.maketrans({'%':''})).astype(float)
Upvotes: 2
Reputation: 71560
Why not str.rstrip()
:
df['Grade'] = df['Grade'].str.rstrip('%')
Upvotes: 5
Reputation: 28321
Using str.replace
would work:
df['Grade'] = df['Grade'].str.replace('%', '')
Upvotes: 24