Python 类型错误:无法将系列转换为 <class 'float'>

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42988348/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 22:22:53  来源:igfitidea点击:

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

pythonpython-3.x

提问by Stacey

I have a dataframe (df) that looks like:

我有一个看起来像的数据框(df):

date                 A
2001-01-02      1.0022
2001-01-03      1.1033
2001-01-04      1.1496
2001-01-05      1.1033

2015-03-30    126.3700
2015-03-31    124.4300
2015-04-01    124.2500
2015-04-02    124.8900

For the entire time-series I'm trying to divide today's value by yesterdays and log the result using the following:

对于整个时间序列,我试图将今天的值除以昨天的值并使用以下命令记录结果:

df["B"] = math.log(df["A"] / df["A"].shift(1))

However I get the following error:

但是我收到以下错误:

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

How can I fix this? I've tried to cast as float using:

我怎样才能解决这个问题?我尝试使用以下方法将其转换为浮点数:

df["B"] .astype(float)

But can't get anything to work.

但不能得到任何工作。

回答by user3582076

You can use numpy.log instead. Math.log is expecting a single number, not array.

您可以改用 numpy.log。Math.log 需要一个数字,而不是数组。

回答by William Welsh

If you just write df["A"].astype(float)you will not change df. You would need to assign the output of the astypemethod call to something else, including to the existing series using df['A'] = df['A'].astype(float). Also you might want to either use numpy as @user3582076 suggests, or use .applyon the Series that results from dividing today's value by yesterday's.

如果你只是写df["A"].astype(float)你不会改变df。您需要将astype方法调用的输出分配给其他内容,包括使用df['A'] = df['A'].astype(float). 此外,您可能希望按照@user3582076 的建议使用 numpy,或者.apply在将今天的值除以昨天的值所得的系列上使用。

回答by Laura Baker

I had the same issue, for me the answer was to look at the cause of why I had series in the first place. After looking for a long time about how to change the series into the different assigned data type, I realised that I had defined the same column name twice in the dataframe and that was why I had a series.

我有同样的问题,对我来说,答案是首先看看为什么我有系列的原因。在寻找了很长时间关于如何将系列更改为不同的指定数据类型之后,我意识到我在数据框中定义了两次相同的列名,这就是我有一个系列的原因。

Removing the accidental duplication of column name removes this issue :)

删除列名的意外重复可以解决此问题:)