Search code examples
pythonpandasdataframeseries

How to convert a series of one value to float only?


I have a series which has only one value and I want to get that value only. I ran a code to get the value by index matching and I got a series like this:

(normal_sum['KWH'][(normal_sum['KWH'].index == date)])

Timestamp
2017-04-02    2934.93
Freq: D, Name: KWH, dtype: float64

But when I tried to convert it into a float like this,

float(normal_sum['KWH'][(normal_sum['KWH'].index == date)])

it is throwing an error:

TypeError: cannot convert the series to <type 'float'>

The expected output is simply the number itself, not in any table or array:

2934.93

Any help would be appreciated.


Also, I am facing another problem:

Suppose I get an empty series. Then how can I convert it to zero?

When I do this,

(normal_sum['KWH'][(normal_sum['KWH'].index == date)])

I get a series like this:

Series([], Freq: D, Name: KWH, dtype: float64)

Solution

  • Use loc

    normal_sum.loc[date, 'KWH']
    

    See @MaxU's answer for at


    Also get_value

    normal_sum.get_value(date, 'KWH')
    

    To return zero when date isn't in the index, you can

    normal_sum.KWH.get(date, 0)