Converting a string to float for a pandas.core.series.Series

I am trying to convert the following pandas.core.series.Series to a float. Code:

from yahoo_fin.options import get_calls
ticker = 'aapl'
ticker_calls = get_calls(ticker)
df = ticker_calls['Implied Volatility']
con = pd.Series(df).astype('float')

also tried:

df.astype('float')
output:

could not convert string to float: ‘733.59%’

when just printing the series/df the data appears:
 
 1. 733.59%
 2. 657.03%
 3. 633.79%
 
however I can't perform any statistics/math on this. The end goal is to be able to do: 

(df[‘Risk_free’] + df[‘IV’])

with the output being: an int or float. example of what I am trying to accomplish:

['Risk_free']0.15 + ['IV']7.3359 = ['new col']7.35089

output I am getting now:

 4. 1.500%733.59%
 5. 1.500%657.03%

Answer

You can strip off the ‘%’ sign..

from yahoo_fin.options import get_calls
ticker = 'aapl'
ticker_calls = get_calls(ticker)
df = ticker_calls['Implied Volatility']
con = df.str.rstrip('%').astype(float)

Sample:

df = pd.Series(['12%', '12.5%', '35%', '50%', '88.880%'])
df.str.rstrip('%').astype(float)
0    12.00
1    12.50
2    35.00
3    50.00
4    88.88
dtype: float64

Leave a Reply

Your email address will not be published. Required fields are marked *