【问题标题】:'float' object has no attribute 'item' when trying to map on series'float' 对象在尝试映射系列时没有属性 'item'
【发布时间】:2020-09-25 01:41:32
【问题描述】:

当我尝试将 float64 转换为单个值的浮点数时,它工作正常 -

import pandas as pd
a=pd.DataFrame()
a['Num']=['1','2','3','4']
a

def float(x):
    return x.item()

float(a['Num'].astype('float')[1])

“浮点”格式的输出 = 2.0

当我在系列上尝试相同时,它会抛出错误''float' object has no attribute 'item'' -

b=map(float,a['Num'].astype('float64'))
print(list(b))

请帮忙!

【问题讨论】:

  • 不阅读任何其他内容,避免在 Python 中调用 float

标签: python pandas floating-point int


【解决方案1】:

不要将函数命名为“float”。

在第一种情况下,您使用 numpy

import pandas as pd
a=pd.DataFrame()
a['Num']=['1','2','3','4']

def to_float(x):
    print(type(x))
    return x.item()

to_float(a['Num'].astype('float')[1])
<class 'numpy.float64'>
2.0

但是当你打电话时

list(map(to_float,a['Num'].astype('float64')))

你有错误,因为类浮动没有属性'item'

<class 'float'>

你可以试试:

a['Num'].map(to_float)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-06
    • 2016-12-02
    • 2018-06-02
    • 2020-03-25
    • 2019-12-31
    相关资源
    最近更新 更多