简体   繁体   中英

pandas.core.series.Series to float

I am new to python and been struggling with this simple code:

So in the last line, I got the object type: pandas.core.series.Series But this type is causing an error when I use it in 2D arrays, how to use the 'ticker' definition to get float in my results?

I know I can simply write like this, so my result is float:

Volatility = sec_returns['GME'].std() * 250 ** 0.5

so 'GME' in the brackets instead of ticker, but I want to use ticker definition, so I can change the ticker. thank you \

ticker = ['GME']
sec_data = pd.DataFrame()
for t in ticker:
    sec_data[t] = wb.DataReader(t, data_source = 'yahoo', start ='2007-01-01')['Adj Close']
sec_returns = np.log(sec_data / sec_data.shift(1))
Volatility = sec_returns[ticker].std() * 250 ** 0.5
print(Volatility)
type(Volatility)
Output: pandas.core.series.Series

Your example is doing two different things when it comes to subsetting a DataFrame.

Volatility = sec_returns['GME'].std() * 250 ** 0.5

Is not the same as:

ticker = ['GME']
Volatility = sec_returns[ticker].std() * 250 ** 0.5

Because in the first instance you're subsetting by passing a string to the DataFrame with a column name and in the second you're subsetting using a lists of strings. So the second instance actually looks like this:

Volatility = sec_returns[['GME']].std() * 250 ** 0.5

This returns a pd.Series rather than a float . To get the value from the pd.Series you can do:

ticker = ['GME']
Volatility = sec_returns[ticker].std() * 250 ** 0.5
Volatility.values[0]

.values returns the series as a numpy array from which we retrieve the first item.

tried all methods suggested here but sadly none worked. Instead, found this to be working:

df['column'] = pd.to_numeric(df['column'],errors = 'coerce')

And then check it using:

print(df.info())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM