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.
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.
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.
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 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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With