Python &引用;TypeError:len()为未调整大小的对象;对数组使用insert时

Python &引用;TypeError:len()为未调整大小的对象;对数组使用insert时,python,numpy,typeerror,Python,Numpy,Typeerror,目标:在数组中的给定索引位置插入一行(i) 使用的语言:带numpy库的python 例如: i=2.0; a=array([[1,2,3],[2,3,4],[3,4,5],[6,7,8]],dtype=float); a=insert(a,i,[-1,-1,-1],axis=0); 这就产生了错误:TypeError:len()(未调整大小的对象) 有什么想法吗?如果您查看文档中的insert: >>> help(insert) 你会发现: Parameters ----

目标:在数组中的给定索引位置插入一行(i)

使用的语言:带numpy库的python

例如:

i=2.0;
a=array([[1,2,3],[2,3,4],[3,4,5],[6,7,8]],dtype=float);
a=insert(a,i,[-1,-1,-1],axis=0);
这就产生了错误:
TypeError:len()(未调整大小的对象)


有什么想法吗?

如果您查看文档中的
insert

>>> help(insert)
你会发现:

Parameters
----------
arr : array_like
    Input array.
obj : int, slice or sequence of ints
    Object that defines the index or indices before which `values` is
    inserted.
values : array_like
    Values to insert into `arr`. If the type of `values` is different
    from that of `arr`, `values` is converted to the type of `arr`.
axis : int, optional
    Axis along which to insert `values`.  If `axis` is None then `arr`
    is flattened first.
看看您所做的,很明显问题在于
obj
必须是一个int、slice或int序列,而不是浮点(
i=2.0

如果设置
i=2
,则示例不会引发错误。我不知道这是否是您想要的,因为您没有说明所需的输出。

我发现了错误。 它给出了错误i=2.0是一个索引,也是一个float,这让python感到困惑

解决方案是将insert()的index属性类型转换为int

这与问题的示例相同:

代码:


需要注意的是,numpy版本1.8.1对int进行隐式转换,因此不会为OP的代码引发该错误

>>> import numpy as np
>>> np.__version__
1.8.1
OP代码-

>>> i = 2.0;
>>> a = np.array([[1,2,3],[2,3,4],[3,4,5],[6,7,8]],dtype=float);
>>> a = np.insert(a,i,[-1,-1,-1],axis=0);


>>> a 
array([[ 1.,  2.,  3.],
       [ 2.,  3.,  4.],
       [-1., -1., -1.],
       [ 3.,  4.,  5.],
       [ 6.,  7.,  8.]])

也许你能告诉我们你用的是什么语言?这通常是通过编辑问题,将语言作为标记之一(现在是“typeerror”)来完成的。另外,如果有多个常用的实现,您可能希望告诉我们您使用的是哪一个。我已经找到了解决方案,但堆栈溢出不允许我在8小时后发布。。“i=int(2.0)”
2
int(2.0)
更有意义,而且Python中不需要这些分号。
>>> i = 2.0;
>>> a = np.array([[1,2,3],[2,3,4],[3,4,5],[6,7,8]],dtype=float);
>>> a = np.insert(a,i,[-1,-1,-1],axis=0);


>>> a 
array([[ 1.,  2.,  3.],
       [ 2.,  3.,  4.],
       [-1., -1., -1.],
       [ 3.,  4.,  5.],
       [ 6.,  7.,  8.]])