Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 546
Dheeraj Avatar asked Jul 21 '17 07:07

Dheeraj


People also ask

How do you convert a column into a float in a data frame?

Alternatively, you can convert all string columns to float type using pandas. to_numeric() . For example use df['Discount'] = pd. to_numeric(df['Discount']) function to convert 'Discount' column to float.

How do you convert data to float in Python?

We can convert a string to float in Python using the float() function. This is a built-in function used to convert an object to a floating point number. Internally, the float() function calls specified object __float__() function.

How do you turn a series object into a list?

How to use the tolist() method to convert pandas series to list. To convert a pandas Series to a list, simply call the tolist() method on the series which you wish to convert.

How do you change the data type of a series?

Change data type of a series in PandasUse a numpy. dtype or Python type to cast entire pandas object to the same type. Alternatively, use {col: dtype, …}, where col is a column label and dtype is a numpy. dtype or Python type to cast one or more of the DataFrame's columns to column-specific types.


2 Answers

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)
like image 200
piRSquared Avatar answered Oct 20 '22 15:10

piRSquared


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
like image 28
MaxU - stop WAR against UA Avatar answered Oct 20 '22 17:10

MaxU - stop WAR against UA