ValueError:使用序列设置数组元素
为什么以下代码示例:
np.array([[1, 2], [2, 3, 4]])
np.array([1.2, "abc"], dtype=float)
全部给出以下错误?
ValueError: setting an array element with a sequence.
Why do the following code samples:
np.array([[1, 2], [2, 3, 4]])
np.array([1.2, "abc"], dtype=float)
all give the following error?
ValueError: setting an array element with a sequence.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(11)
错误是因为 np.array 函数的 dtype 参数指定了数组中元素的数据类型,并且只能将其设置为与所有元素兼容的单一数据类型。值“abc”不是有效的浮点数,因此尝试将其转换为浮点数会导致 ValueError。为了避免此错误,您可以从列表中删除字符串元素,或者选择可以同时处理浮点值和字符串值的不同数据类型,例如 object.
The error is because the dtype argument of the np.array function specifies the data type of the elements in the array, and it can only be set to a single data type that is compatible with all the elements. The value "abc" is not a valid float, so trying to convert it to a float results in a ValueError. To avoid this error, you can either remove the string element from the list, or choose a different data type that can handle both float values and string values, such as object.
可能的原因 1:尝试创建锯齿状数组
您可能从形状不像多维数组的列表创建数组:
在这些示例中,
numpy.array
的参数包含序列不同长度的。这些将产生此错误消息,因为输入列表的形状不像可以转换为多维数组的“盒子”。可能的原因2:提供不兼容类型的元素
例如,提供字符串作为
float
类型数组中的元素:如果你确实想要一个同时包含字符串和浮点数的NumPy数组,你可以使用dtype
object
,它允许数组保存任意 Python 对象:Possible reason 1: trying to create a jagged array
You may be creating an array from a list that isn't shaped like a multi-dimensional array:
In these examples, the argument to
numpy.array
contains sequences of different lengths. Those will yield this error message because the input list is not shaped like a "box" that can be turned into a multidimensional array.Possible reason 2: providing elements of incompatible types
For example, providing a string as an element in an array of type
float
:If you really want to have a NumPy array containing both strings and floats, you could use the dtype
object
, which allows the array to hold arbitrary Python objects:Python ValueError:
顾名思义,您正在尝试将一系列数字塞入单个数字槽中。它可以在各种情况下抛出。
1.当您传递一个 python 元组或列表以将其解释为 numpy 数组元素时:
2.通过尝试填充 numpy 数组 length > 1 到 numpy 数组元素中:
正在创建 numpy 数组,numpy 不知道如何将多值元组或数组填充到单个元素槽中。它期望您给它的任何内容都计算为单个数字,如果不是,Numpy 会响应它不知道如何使用序列设置数组元素。
The Python ValueError:
Means exactly what it says, you're trying to cram a sequence of numbers into a single number slot. It can be thrown under various circumstances.
1. When you pass a python tuple or list to be interpreted as a numpy array element:
2. By trying to cram a numpy array length > 1 into a numpy array element:
A numpy array is being created, and numpy doesn't know how to cram multivalued tuples or arrays into single element slots. It expects whatever you give it to evaluate to a single number, if it doesn't, Numpy responds that it doesn't know how to set an array element with a sequence.
就我而言,我在 Tensorflow 中遇到此错误,原因是我试图提供具有不同长度或序列的数组:
示例:
如果我的数组是:
那么我会收到错误:
但如果我进行填充,那么:
现在它正在工作。
In my case , I got this Error in Tensorflow , Reason was i was trying to feed a array with different length or sequences :
example :
And if my array is :
Then i will get error :
but if i do padding then :
Now it's working.
对于那些在 Numpy 中遇到类似问题的人,一个非常简单的解决方案是:
在定义用于为其赋值的数组时定义 dtype=object 。例如:
for those who are having trouble with similar problems in Numpy, a very simple solution would be:
defining
dtype=object
when defining an array for assigning values to it. for instance:就我而言,问题是另一个。我试图将 int 列表的列表转换为数组。问题在于,有一个列表的长度与其他列表的长度不同。如果你想证明这一点,你必须这样做:
在我的例子中,长度参考是560。
In my case, the problem was another. I was trying convert lists of lists of int to array. The problem was that there was one list with a different length than others. If you want to prove it, you must do:
In my case, the length reference was 560.
就我而言,问题出在数据框 X[] 的散点图上:
In my case, the problem was with a scatterplot of a dataframe X[]:
发生此错误的一个常见原因是当您想要使用
将数组的数据类型从
object
更改为int
/float
等时astype() 调用。可能有两种情况:a) 锯齿状数组
最常见的情况是数组呈锯齿状。在这种情况下,“内部”数组可能需要在更改数据类型之前展平。
b) “内部”数组未正确读取
另一种常见情况是当
object
数据类型数组的“内部”数组未正确读取时,即使形状和数据类型看似正常,也会导致此错误。例如,在下面的情况下,
arr
的“内部”数组具有相同的形状(并且也具有相同的数据类型),因此我们还没有锯齿数组问题当调用astype(int)
时,我们在标题中收到错误。本例中,将
arr
转换为列表,稍后再转换为ndarray;或者只是stack()
它。当尝试使用
astype()
将包含列表/ndarray 的 pandas 列转换为 numpy ndarray 时,通常会发生此错误。换句话说,如果您想使用astype()
进行以下转换,就会发生这种情况。在这种情况下,请使用
stack()
或转换为列表并转换为 ndarray,而不是astype()
。np.where()
/np.nonzero()
返回一个元组发生此错误的另一个常见示例是当您想要分配从 np 返回的值时。 where() 到一个数组。但是,np.where()当仅传递条件时返回一个元组(与np.nonzero()相同),这会导致此错误,原因相同Eric Leschinski 的回答中进行了解释。在这种情况下,仅分配元组中的相关值(在下面的示例中,这是元组中的第一项)。
A common reason this error occurs is when you want to change the dtype of an array from
object
toint
/float
etc using anastype()
call. There could be two cases:a) jagged array
The most common case is when the array is jagged. In this case, the "inner" array probably needs to be flattened before changing the dtype.
b) "inner" arrays are not read properly
Another common case is when an
object
dtype array's "inner" arrays are not read properly, which causes this error even if the shapes and dtypes are seemingly a-OK.For example in the following case, the "inner" arrays of
arr
have the same shape (and have the same dtype as well), so we don't have the jagged array problem, yet when callingastype(int)
, we get the error in the title.In this case, convert
arr
into a list and convert to an ndarray later; or juststack()
it.This error commonly occurs when a pandas column that contained lists/ndarrays are attempted to be converted into a numpy ndarray using
astype()
. In other words, it occurs if you want to make the following conversion usingastype()
.In this case, instead of
astype()
, usestack()
or convert to a list and cast to an ndarray.np.where()
/np.nonzero()
returns a tupleAnother common example where this error occurs is when you want to assign the values returned from
np.where()
to an array. However,np.where()
when only the condition is passed returns a tuple (same withnp.nonzero()
), which leads to this error, for the same reason explained in Eric Leschinski's answer. In this case, assign only the relevant value from the tuple (in the example below, that is the first item in the tuple).当形状不规则或元素具有不同的数据类型时,传递给np.array的
dtype
参数只能是object
。``
When the shape is not regular or the elements have different data types, the
dtype
argument passed to np.array only can beobject
.``
就我而言,我有一个嵌套列表作为我想用作输入的系列。
首先检查:如果
输出类似
[1,2,3]
的列表,则您有一个嵌套列表。然后检查更改为输入
df['nestedList'][0]
时是否仍然出现错误。那么您的下一步可能是将所有嵌套列表连接到一个非嵌套列表中,使用
嵌套列表的扁平化借自 如何从列表列表中制作平面列表?。
In my case, I had a nested list as the series that I wanted to use as an input.
First check: If
outputs a list like
[1,2,3]
, you have a nested list.Then check if you still get the error when changing to input
df['nestedList'][0]
.Then your next step is probably to concatenate all nested lists into one unnested list, using
This flattening of the nested list is borrowed from How to make a flat list out of list of lists?.
就我而言,这是版本问题。我收到 numpy 版本 = 1.24.1 的错误。但当我降级到1.21.6时,问题就解决了。
In my case, it was a version problem. I got the error for numpy version = 1.24.1. But when I downgraded to 1.21.6, the problem was fixed.