【问题标题】:TypeError: len() of unsized object when converting object to numericTypeError:将对象转换为数字时未调整大小的对象的 len()
【发布时间】:2018-07-16 09:56:09
【问题描述】:

我正在处理具有以下形式的列的数据框:

allHoldingsFund['ratioBest']

Out[72]: 
65357                     0.0
65371                     0.0
65394       2.396777442094666
65397                     0.0
65433      0.0167993412023058
65462                     0.0
65560                     0.0
Name: ratioBest, Length: 1664, dtype: object

列是一个对象,我通常使用allHoldingsFund['ratioBest']=pd.to_numeric(allHoldingsFund['ratioBest'])将对象转换为数值

但是,当我这样做时,我得到了一个我无法解决的错误:

pd.to_numeric(allHoldingsFund['ratioBest'])
Traceback (most recent call last):
  File "/apps/qtrinst/install/python/anaconda/envs/sx_anaconda/lib/python3.5/site-packages/IPython/core/interactiveshell.py", line 2910, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-71-6f0ccaf63f24>", line 1, in <module>
    pd.to_numeric(allHoldingsFund['ratioBest'])
  File "/apps/qtrinst/install/python/anaconda/envs/sx_anaconda/lib/python3.5/site-packages/pandas/core/tools/numeric.py", line 133, in to_numeric
    coerce_numeric=coerce_numeric)
  File "pandas/_libs/src/inference.pyx", line 1111, in pandas._libs.lib.maybe_convert_numeric
TypeError: len() of unsized object

请问我该如何解决这个问题?

【问题讨论】:

  • allHoldingsFund['ratioBest']=pd.to_numeric(allHoldingsFund['ratioBest'], errors='coerce') 工作怎么样?
  • @jezrael 谢谢。它工作正常。但是,它仍然是一个对象。它没有被转换成浮点数,这使得该列不能用于其他目的
  • 所以print (allHoldingsFund['ratioBest'].dtype) 再次返回object ?
  • 是的print (allHoldingsFund['ratioBest'].dtype) object我也可以从这个操作中看出哪个不起作用np.where(allHoldingsFund['ratioBest']&gt;1,1,0)
  • 对我来说效果很好

标签: python python-3.x pandas numeric


【解决方案1】:

函数to_numeric 将参数转换为数值类型。 您得到的错误 len() of unsized object 仅在计算 len() 之类的 int 值时出现。因此,对您的错误的唯一解释是您存储该列的任何数据结构,其中部分或全部已经以 float 的形式存储,因为 pandas 试图找到它的长度并得到上述错误。

【讨论】:

  • 我不同意,因为如果只有浮动,那么 OP 应该得到Name: ratioBest, Length: 1664, dtype: float64,而不是Name: ratioBest, Length: 1664, dtype: object,而且如果只有浮动pd.to_numeric 工作得很好。在我看来,这似乎是错误。
  • allHoldingsFund['ratioBest'] 列是使用 np.where 创建的。基本上,如果值存在,那么如果它们不存在,我将取这些值的比率,我只需将比率设置为零。 allHoldingsFund['ratioBest']=np.where (if values exist, take the ratio, 0 )
  • @jezrael 为什么会出错?
  • @SBad - 因为奇怪的错误。我的解决方案不起作用?
  • 我的回答完全基于您的堆栈跟踪,您来了,这就是您的问题:I just set the ratio to zero.。 Pandas 肯定会尝试查找每个元素的长度,这就是您尝试查找 int 0 的长度时导致的错误。试试'0',你应该很高兴。
【解决方案2】:

对我来说工作很好的参数errors='coerce' 用于将无数字转换为NaNs:

allHoldingsFund = pd.DataFrame({'ratioBest':[['123'], '123', 'aaa']})

allHoldingsFund['ratioBest'] = pd.to_numeric(allHoldingsFund['ratioBest'], errors='coerce')
print (allHoldingsFund)
   ratioBest
0        NaN
1      123.0
2        NaN

print (allHoldingsFund['ratioBest'].dtypes)
float64

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-14
    • 1970-01-01
    • 2013-07-19
    • 1970-01-01
    • 2011-12-01
    • 1970-01-01
    相关资源
    最近更新 更多