pandas 如何将一系列一个值转换为仅浮点数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/45231441/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert a series of one value to float only?
提问by Dheeraj
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
预期输出: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.
请帮忙。
采纳答案by piRSquared
Use loc
用 loc
normal_sum.loc[date, 'KWH']
See @MaxU's answer for at
请参阅@MaxU 的回答 at
Also get_value
还 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)
回答by MaxU
we can use Series.at[...]method for scalarlookup:
我们可以使用Series.at[...]方法进行标量查找:
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
回答by Nathan
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['KWH']),您可以这样做:
normal_sum.iloc[0,0]
or
或者
normal_sum.loc[date, 'KWH']