【发布时间】:2018-04-25 13:45:44
【问题描述】:
我正在尝试根据在单独的数组中定义的一些先前定义的条件对数据帧进行切片。在遍历该数组以查找数据帧的相关切片时,我遇到了问题。第一次迭代工作正常,但在第二次迭代期间循环中断,抛出TypeError: len() of unsized object。
这是一个示例数据框:
std sterr Z smooth
0 5.1 2.28 0 7.640484
1 5.13 2.29 0.1 7.532409
2 5.15 2.3 0.21 7.406423
3 5.17 2.31 0.31 7.267842
4 5.19 2.32 0.42 7.121988
5 5.21 2.33 0.52 6.974179
6 5.23 2.34 0.62 6.829734
7 5.25 2.35 0.73 6.693973
8 5.27 2.36 0.83 6.584009
9 5.29 2.37 0.94 6.49429
10 5.31 2.38 1.04 6.427032
这是循环的代码:
turnz = df.ix[np.array(turn_iloc), 'Z']
c = 0.
print "turn points", np.array(turnz)
for i, zi in enumerate(np.array(turnz)):
z0 = c
print z0, zi, type(z0), type(zi)
x = df.loc[((z0<=df['Z'])& (df['Z']<=zi)), 'Z']
y = df.loc[((z0<=df['Z'])& (df['Z']<=zi)), 'smooth']
print len(x), len(y)
print type(x), type(y)
c = zi
这些是打印输出:
turn points [ 1.04 2.19 2.5 4.06]
0.0 1.04 <type 'float'> <type 'numpy.float64'>
11 11
<class 'pandas.core.series.Series'> <class 'pandas.core.series.Series'>
1.04 2.19 <type 'numpy.float64'> <type 'numpy.float64'>
在此之后,它会引发错误。 但是,如果我尝试在循环外使用这些打印值对数据框进行切片,则效果很好。
print "IS IT",df.loc[((1.04<=df['Z'])& (df['Z']<=2.19)), 'Z']
打印
IS IT 10 1.04
11 1.14
12 1.25
13 1.35
14 1.46
15 1.56
16 1.67
17 1.77
18 1.87
19 1.98
20 2.08
21 2.19
Name: Z, dtype: float64
我错过了什么?
如果有帮助,完整的回溯如下:
TypeError Traceback (most recent call last)
<ipython-input-18-b6d427f5dae7> in <module>()
9 z0 = c
10 print z0, zi, type(z0), type(zi)
---> 11 x = df.loc[((z0<=df['Z'])& (df['Z']<=zi)), 'Z']
12 y = df.loc[((z0<=df['Z'])& (df['Z']<=zi)), 'smooth']
13 print len(x), len(y)
C:\Users\me\AppData\Local\Continuum\Anaconda2\lib\site-packages\pandas\core\ops.pyc in wrapper(self, other, axis)
739 return NotImplemented
740 elif isinstance(other, (np.ndarray, pd.Index)):
--> 741 if len(self) != len(other):
742 raise ValueError('Lengths must match to compare')
743 return self._constructor(na_op(self.values, np.asarray(other)),
TypeError: len() of unsized object
结果
事实证明,我的数据框无法使用 numpy 浮点数进行切片。将z0 和zi 转换为float 即可解决问题!
【问题讨论】:
-
ix已弃用...试试loc? -
loc仅适用于键,iloc仅适用于索引。除了使用ix,我还能将两者结合起来吗?此外,如果这是问题所在,为什么它在第一次迭代中起作用? (我试过了,并没有解决问题) -
不,
loc也适用于布尔掩码。iloc没有。 -
我刚刚测试了你的代码,它执行没有错误。我所做的唯一修改是:
turnz=[ 1.04, 2.19, 2.5, 4.06]; cislo=1.04并包装了print语句以兼容 Python 3。使用 Pandas 0.20.3 和 Python 3.6。我确实收到了关于.ix被弃用的警告,但没有错误。如果你像我一样静态定义turnz,而不从df中提取它的值,你还会得到错误吗? -
@durbachit,好!考虑写下你自己的答案并接受它。如果您能弄清楚
float64导致问题的原因,那就更好了...