TypeError: len() of unsized object when comparing and I cannot make sense of it

TypeError: len() of unsized object when comparing and I cannot make sense of it

我正在尝试 select 传感器,方法是在其地理坐标周围放置一个方框:

In [1]: lat_min, lat_max = lats(data)
        lon_min, lon_max = lons(data)

        print(np.around(np.array([lat_min, lat_max, lon_min, lon_max]), 5))
Out[1]: [ 32.87248  33.10181 -94.37297 -94.21224]

In [2]: select_sens = sens[(lat_min<=sens['LATITUDE']) & (sens['LATITUDE']<=lat_max) &
                           (lon_min<=sens['LONGITUDE']) & (sens['LONGITUDE']<=lon_max)].copy()
Out[2]: ---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-12-7881f6717415> in <module>()
      4 lon_min, lon_max = lons(data)
      5 select_sens = sens[(lat_min<=sens['LATITUDE']) & (sens['LATITUDE']<=lat_max) &
----> 6                    (lon_min<=sens['LONGITUDE']) & (sens['LONGITUDE']<=lon_max)].copy()
      7 sens_data = data[data['ID'].isin(select_sens['ID'])].copy()
      8 sens_data.describe()

/home/kartik/miniconda3/lib/python3.5/site-packages/pandas/core/ops.py in wrapper(self, other, axis)
    703             return NotImplemented
    704         elif isinstance(other, (np.ndarray, pd.Index)):
--> 705             if len(self) != len(other):
    706                 raise ValueError('Lengths must match to compare')
    707             return self._constructor(na_op(self.values, np.asarray(other)),

TypeError: len() of unsized object

当然,sens 是一个 pandas DataFrame。即使我使用 .where() 它也会引发相同的错误。我完全被难住了,因为这是一个简单的比较,不应该引发任何错误。甚至数据类型匹配:

In [3]: sens.dtypes
Out[3]: ID              object
        COUNTRY         object
        STATE           object
        COUNTY          object
        LENGTH         float64
        NUMBER          object
        NAME            object
        LATITUDE       float64
        LONGITUDE      float64
        dtype: object

所以这是怎么回事?!?

-----编辑----- 根据 Ethan Furman 的回答,我做了以下更改:

In [2]: select_sens = sens[([lat_min]<=sens['LATITUDE']) & (sens['LATITUDE']<=[lat_max]) &
                           ([lon_min]<=sens['LONGITUDE']) & (sens['LONGITUDE']<=[lon_max])].copy()

并且(鼓声)它奏效了...但是为什么呢?

我不熟悉 NumPy 也不熟悉 Pandas,但错误是说比较 if len(self) != len(other) 中的对象之一没有 __len__ 方法,因此有没有长度。

尝试 print(sens_data) 看看是否会出现类似的错误。

我发现了一个类似的问题,我认为这个问题可能与您使用的 Python 版本有关。

我用 Spyder 写代码 Python 3.6.1 |Anaconda 4.4.0(64 位)

但随后将其传递给使用 Spyder 的人,但 Python 3.5.2 |Anaconda 4.2.0(64 位)

我有一个 numpy.float64 对象(据我所知,类似于代码中的 lat_min、lat_max、lon_min 和 lon_max ) MinWD.MinWD[i]

In [92]: type(MinWD.MinWD[i])
Out[92]: numpy.float64

和一个 Pandas 数据框 WatDemandCur,其中有一列名为 Percentages

In [96]: type(WatDemandCur)
Out[96]: pandas.core.frame.DataFrame

In [98]: type(WatDemandCur['Percentages'])
Out[98]: pandas.core.series.Series

我想做以下比较

In [99]: MinWD.MinWD[i]==WatDemandCur.Percentages

当运行我机器中的代码(Python 3.6.1)

时,这一行没有问题

但是我的朋友在(Python 3.5.2)

MinWD.MinWD[i]==WatDemandCur.Percentages
Traceback (most recent call last):

  File "<ipython-input-99-3e762b849176>", line 1, in <module>
    MinWD.MinWD[i]==WatDemandCur.Percentages

  File "C:\Program Files\Anaconda3\lib\site-packages\pandas\core\ops.py", line 741, in wrapper
    if len(self) != len(other):

TypeError: len() of unsized object

我对他的问题的解决方案是将代码更改为

[MinWD.MinWD[i]==x for x in WatDemandCur.Percentages] 

并且它在两个版本中都有效!

有了这个和你的证据,我认为不可能将 numpy.float64 和 numpy.integers 对象与 Pandas 系列进行比较,这可能部分与事实上,前者没有 len 功能。

出于好奇,我用float和integer对象做了一些测试(请区分numpy.float64对象)

In [122]: Temp=1

In [123]: Temp2=1.0

In [124]: type(Temp)
Out[124]: int

In [125]: type(Temp2)
Out[125]: float

In [126]: len(Temp)
Traceback (most recent call last):

  File "<ipython-input-126-dc80ab11ca9c>", line 1, in <module>
    len(Temp)

TypeError: object of type 'int' has no len()


In [127]: len(Temp2)
Traceback (most recent call last):

  File "<ipython-input-127-a1b836f351d2>", line 1, in <module>
    len(Temp2)

TypeError: object of type 'float' has no len()

Temp==WatDemandCur.Percentages

Temp2==WatDemandCur.Percentages

两者都有效!

结论

  1. 在另一个 python 版本中,您的代码应该可以工作!
  2. 比较的问题是 numpy.floats 和 numpy.integers
  3. 特有的
  4. 当你包含 [] 或当我用我的解决方案创建列表时,对象类型从 numpy.float 更改为列表,这样它就可以正常工作。
  5. 尽管问题似乎与 numpy.float64 个对象没有 len 函数、浮点数和整数(也没有 len 函数)这一事实有关。

希望其中一些对您或其他面临类似问题的人有用。