【问题标题】:TypeError: cannot convert the series to <class 'float'> when using exp function [duplicate]TypeError:使用 exp 函数时无法将系列转换为 <class 'float'> [重复]
【发布时间】:2017-10-16 03:45:31
【问题描述】:

我有数据框“子集”,它是较大数据框的前 50 列。我正在尝试对通过将一列的值除以另一列中的值形成的数字使用 exp 函数:

import math
subset['exp'] = math.exp(subset['A'] / subset['B'])

但是这会返回以下错误:

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

我很困惑,因为这两列都是我测试过的浮点类型:

df['A'].dtype

我什至尝试使用 float 函数转换它们(即使它们看起来已经是浮点数):

 subset['exp'] = math.exp(float(subset['A']) / float(subset['B']))

但这会产生同样的错误!

任何帮助表示赞赏

【问题讨论】:

    标签: python pandas types typeerror


    【解决方案1】:

    就像 DYZ 指出的那样,您可以使用numpy 并得到以下结果:

    subset['exp'] = np.exp(subset['A'] / subset['B'])
    

    另外,如果你想留在math.exp,你可以选择apply

    subset['exp'] = subset.apply(lambda x: math.exp(x.A / x.B), axis=1)
    

    apply 循环遍历行或您的dataframe。但是,这种方法在dataframe 很大的情况下并不是最快的。

    【讨论】:

      【解决方案2】:

      math.exp() 需要一个浮点数,而您传递的是 Series。使用numpy.exp()(math.exp() 的矢量化版本)。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-08-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-24
        相关资源
        最近更新 更多