首页 > 解决方案 > 'float' 对象在 python 中不可迭代

问题描述

我有以下功能:

def cambiar_tamano(size):
if 'M' in size:
    x = size[:-1]
    x = float(x)*1000000
    return(x)
elif 'k' == size[-1:]:
    x = size[:-1]
    x = float(x)*1000
    return(x)
else:
    return None

旨在转换大小。例如,将“25M”转换为数值。但是当我尝试实现它时,我得到了这个错误:

TypeError: 'float' object is not iterable

编辑:这是数据框结构

数据框

对函数的调用:

data_store["Size"] = data_store["Size"].map(cambiar_tamano)

作为“data_store”数据框的名称和跟踪:

    TypeError                                 Traceback (most recent call last)
<ipython-input-35-abbd67041e83> in <module>()
      7 #print(Size)
      8 
----> 9 data_store["Size"] = data_store["Size"].map(cambiar_tamano)
     10 data_store.Size.fillna(method = 'ffill', inplace = True)

~\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\core\series.py in map(self, arg, na_action)
   2996         """
   2997         new_values = super(Series, self)._map_values(
-> 2998             arg, na_action=na_action)
   2999         return self._constructor(new_values,
   3000                                  index=self.index).__finalize__(self)

~\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\core\base.py in _map_values(self, mapper, na_action)
   1002 
   1003         # mapper is a function
-> 1004         new_values = map_f(values, mapper)
   1005 
   1006         return new_values

pandas/_libs/src\inference.pyx in pandas._libs.lib.map_infer()

<ipython-input-34-72b73c9e233b> in cambiar_tamano(size)
      1 def cambiar_tamano(size):
----> 2     if 'M' in size:
      3         x = size[:-1]
      4         x = float(x)*1000000
      5         return(x)

TypeError: argument of type 'float' is not iterable

谢谢!

标签: python

解决方案


错误只是说“TypeError:'float' object is not iterable

尝试传递一个集合,可能是一个字符串,例如。"25M"然后根据需要在提取后等类型转换为所需的数据类型。

参考:
https ://docs.python.org/2/library/exceptions.html#exceptions.TypeError


推荐阅读