简体   繁体   中英

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 t he 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 by this:

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

It is throwing an error:

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

Expected output: 2934.93

Any help would be appreciated.

There is an edit:

I am facing another problem:

Suppose i get an empty series then how can i convert it to zero.

i did this:

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

Got a series like this:

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

please help.

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)

we can use Series.at[...] method for scalar lookup:

In [138]: normal_sum = pd.Series([1.234], index=['KWH'])

In [139]: normal_sum
Out[139]:
KWH    1.234
dtype: float64

In [140]: normal_sum.at['KWH']
Out[140]: 1.234

如果数据系列中只有一个元素,您可以通过调用tolist()并通过引用[0]获取新列表的第一个元素将其转换为列表。

As it says, you are trying to convert a Series to a float which is not possible. Potentially a Series could have several entries, and each of this entry doesn't have to be a float or an integer, it could be anything. So you have to select your specific entry, either with (bad way):

normal_sum['KWH'].loc[0]

or

normal_sum['KWH'].iloc[date]

Edit: Chain indexing done as previously should be avoided, the following way is better.

If you are select directly form the dataframe (and not from the Series normal_sum['KWH']), you can just do:

normal_sum.iloc[0,0]

or

normal_sum.loc[date, 'KWH']

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