ValueError:使用序列设置数组元素

发布于 2024-10-11 13:56:41 字数 244 浏览 4 评论 0原文

为什么以下代码示例:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(11

独自唱情﹋歌 2024-10-18 13:56:42

错误是因为 np.array 函数的 dtype 参数指定了数组中元素的数据类型,并且只能将其设置为与所有元素兼容的单一数据类型。值“abc”不是有效的浮点数,因此尝试将其转换为浮点数会导致 ValueError。为了避免此错误,您可以从列表中删除字符串元素,或者选择可以同时处理浮点值和字符串值的不同数据类型,例如 object.

numpy.array([1.2, "abc"], dtype=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.

numpy.array([1.2, "abc"], dtype=object)
无人问我粥可暖 2024-10-18 13:56:41

可能的原因 1:尝试创建锯齿状数组

您可能从形状不像多维数组的列表创建数组:

numpy.array([[1, 2], [2, 3, 4]])         # wrong!
numpy.array([[1, 2], [2, [3, 4]]])       # wrong!

在这些示例中,numpy.array 的参数包含序列不同长度的。这些将产生此错误消息,因为输入列表的形状不像可以转换为多维数组的“盒子”。

可能的原因2:提供不兼容类型的元素

例如,提供字符串作为float类型数组中的元素:

numpy.array([1.2, "abc"], dtype=float)   # wrong!

如果你确实想要一个同时包含字符串和浮点数的NumPy数组,你可以使用dtype object,它允许数组保存任意 Python 对象:

numpy.array([1.2, "abc"], dtype=object)

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:

numpy.array([[1, 2], [2, 3, 4]])         # wrong!
numpy.array([[1, 2], [2, [3, 4]]])       # wrong!

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:

numpy.array([1.2, "abc"], dtype=float)   # wrong!

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:

numpy.array([1.2, "abc"], dtype=object)
愚人国度 2024-10-18 13:56:41

Python ValueError:

ValueError: setting an array element with a sequence.

顾名思义,您正在尝试将一系列数字塞入单个数字槽中。它可以在各种情况下抛出。

1.当您传递一个 python 元组或列表以将其解释为 numpy 数组元素时:

import numpy

numpy.array([1,2,3])               #good

numpy.array([1, (2,3)])            #Fail, can't convert a tuple into a numpy 
                                   #array element


numpy.mean([5,(6+7)])              #good

numpy.mean([5,tuple(range(2))])    #Fail, can't convert a tuple into a numpy 
                                   #array element


def foo():
    return 3
numpy.array([2, foo()])            #good


def foo():
    return [3,4]
numpy.array([2, foo()])            #Fail, can't convert a list into a numpy 
                                   #array element

2.通过尝试填充 numpy 数组 length > 1 到 numpy 数组元素中:

x = np.array([1,2,3])
x[0] = np.array([4])         #good



x = np.array([1,2,3])
x[0] = np.array([4,5])       #Fail, can't convert the numpy array to fit 
                             #into a numpy array element

正在创建 numpy 数组,numpy 不知道如何将多值元组或数组填充到单个元素槽中。它期望您给它的任何内容都计算为单个数字,如果不是,Numpy 会响应它不知道如何使用序列设置数组元素。

The Python ValueError:

ValueError: setting an array element with a sequence.

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:

import numpy

numpy.array([1,2,3])               #good

numpy.array([1, (2,3)])            #Fail, can't convert a tuple into a numpy 
                                   #array element


numpy.mean([5,(6+7)])              #good

numpy.mean([5,tuple(range(2))])    #Fail, can't convert a tuple into a numpy 
                                   #array element


def foo():
    return 3
numpy.array([2, foo()])            #good


def foo():
    return [3,4]
numpy.array([2, foo()])            #Fail, can't convert a list into a numpy 
                                   #array element

2. By trying to cram a numpy array length > 1 into a numpy array element:

x = np.array([1,2,3])
x[0] = np.array([4])         #good



x = np.array([1,2,3])
x[0] = np.array([4,5])       #Fail, can't convert the numpy array to fit 
                             #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.

我只土不豪 2024-10-18 13:56:41

就我而言,我在 Tensorflow 中遇到此错误,原因是我试图提供具有不同长度或序列的数组:

示例:

import tensorflow as tf

input_x = tf.placeholder(tf.int32,[None,None])



word_embedding = tf.get_variable('embeddin',shape=[len(vocab_),110],dtype=tf.float32,initializer=tf.random_uniform_initializer(-0.01,0.01))

embedding_look=tf.nn.embedding_lookup(word_embedding,input_x)

with tf.Session() as tt:
    tt.run(tf.global_variables_initializer())

    a,b=tt.run([word_embedding,embedding_look],feed_dict={input_x:example_array})
    print(b)

如果我的数组是:

example_array = [[1,2,3],[1,2]]

那么我会收到错误:

ValueError: setting an array element with a sequence.

但如果我进行填充,那么:

example_array = [[1,2,3],[1,2,0]]

现在它正在工作。

In my case , I got this Error in Tensorflow , Reason was i was trying to feed a array with different length or sequences :

example :

import tensorflow as tf

input_x = tf.placeholder(tf.int32,[None,None])



word_embedding = tf.get_variable('embeddin',shape=[len(vocab_),110],dtype=tf.float32,initializer=tf.random_uniform_initializer(-0.01,0.01))

embedding_look=tf.nn.embedding_lookup(word_embedding,input_x)

with tf.Session() as tt:
    tt.run(tf.global_variables_initializer())

    a,b=tt.run([word_embedding,embedding_look],feed_dict={input_x:example_array})
    print(b)

And if my array is :

example_array = [[1,2,3],[1,2]]

Then i will get error :

ValueError: setting an array element with a sequence.

but if i do padding then :

example_array = [[1,2,3],[1,2,0]]

Now it's working.

怕倦 2024-10-18 13:56:41

对于那些在 Numpy 中遇到类似问题的人,一个非常简单的解决方案是:

在定义用于为其赋值的数组时定义 dtype=object 。例如:

out = np.empty_like(lil_img, 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:

out = np.empty_like(lil_img, dtype=object)
别在捏我脸啦 2024-10-18 13:56:41

就我而言,问题是另一个。我试图将 int 列表的列表转换为数组。问题在于,有一个列表的长度与其他列表的长度不同。如果你想证明这一点,你必须这样做:

print([i for i,x in enumerate(list) if len(x) != 560])

在我的例子中,长度参考是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:

print([i for i,x in enumerate(list) if len(x) != 560])

In my case, the length reference was 560.

我的黑色迷你裙 2024-10-18 13:56:41

就我而言,问题出在数据框 X[] 的散点图上:

ax.scatter(X[:,0],X[:,1],c=colors,    
       cmap=CMAP, edgecolor='k', s=40)  #c=y[:,0],

#ValueError: setting an array element with a sequence.
#Fix with .toarray():
colors = 'br'
y = label_binarize(y, classes=['Irrelevant','Relevant'])
ax.scatter(X[:,0].toarray(),X[:,1].toarray(),c=colors,   
       cmap=CMAP, edgecolor='k', s=40)

In my case, the problem was with a scatterplot of a dataframe X[]:

ax.scatter(X[:,0],X[:,1],c=colors,    
       cmap=CMAP, edgecolor='k', s=40)  #c=y[:,0],

#ValueError: setting an array element with a sequence.
#Fix with .toarray():
colors = 'br'
y = label_binarize(y, classes=['Irrelevant','Relevant'])
ax.scatter(X[:,0].toarray(),X[:,1].toarray(),c=colors,   
       cmap=CMAP, edgecolor='k', s=40)
掀纱窥君容 2024-10-18 13:56:41

发生此错误的一个常见原因是当您想要使用 将数组的数据类型从 object 更改为 int/float 等时astype() 调用。可能有两种情况:

  • a) 锯齿状数组

    最常见的情况是数组呈锯齿状。在这种情况下,“内部”数组可能需要在更改数据类型之前展平。

    将 numpy 导入为 np
    arr = np.array([1,2, [3,4]], dtype=对象)
    arr.astype(int) # <--- ValueError: 用序列设置数组元素。
    
    # 展平数组
    输出 = []
    对于 arr 中的 x:
        if isinstance(x, (列表, np.ndarray, 元组)):
            向外扩展(x)
        别的:
            输出.append(x)
    arr = np.array(out) # <--- 好的
    
    b) “内部”数组未正确读取

    另一种常见情况是当 object 数据类型数组的“内部”数组未正确读取时,即使形状和数据类型看似正常,也会导致此错误。

    例如,在下面的情况下,arr 的“内部”数组具有相同的形状(并且也具有相同的数据类型),因此我们还没有锯齿数组问题当调用 astype(int) 时,我们在标题中收到错误。

    arr = np.array([1, 2], dtype=object)
    arr[:2] = [[10], [20]]
    arr # 数组([列表([10]), 列表([20])], dtype=对象)
    
    arr.astype(int) # <--- ValueError: 用序列设置数组元素。
    

    本例中,将arr转换为列表,稍后再转换为ndarray;或者只是stack()它。

    np.array(arr.tolist()) # <--- 好的
    np.stack(arr) # <--- 好的
    

    当尝试使用 astype() 将包含列表/ndarray 的 pandas 列转换为 numpy ndarray 时,通常会发生此错误。换句话说,如果您想使用 astype() 进行以下转换,就会发生这种情况。

    “熊猫案例”

    在这种情况下,请使用 stack() 或转换为列表并转换为 ndarray,而不是 astype()

    导入 pandas 作为 pd
    
    s = pd.Series([[1,2], [3,4]])
    
    s.astype(int) # <--- ValueError: 用序列设置数组元素。
    s.to_numpy().astype(int) # <--- ValueError: 用序列设置数组元素。
    np.array(s.tolist()) # <--- 好的
    np.stack(s) # <--- 好的
    
np.where()/np.nonzero() 返回一个元组

发生此错误的另一个常见示例是当您想要分配从 np 返回的值时。 where() 到一个数组。但是,np.where()当仅传递条件时返回一个元组(与np.nonzero()相同),这会导致此错误,原因相同Eric Leschinski 的回答中进行了解释。在这种情况下,仅分配元组中的相关值(在下面的示例中,这是元组中的第一项)。

arr = np.array([1, 2, 3])

arr[:3] = np.where(arr>0)       # <--- ValueError: ...
arr[:3] = np.where(arr>0)[0]    # <--- OK
arr[:3] = np.nonzero(arr>0)[0]  # <--- OK

A common reason this error occurs is when you want to change the dtype of an array from object to int/float etc using an astype() 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.

    import numpy as np
    arr = np.array([1,2, [3,4]], dtype=object)
    arr.astype(int)             # <--- ValueError: setting an array element with a sequence.
    
    # flatten array
    out = []
    for x in arr:
        if isinstance(x, (list, np.ndarray, tuple)):
            out.extend(x)
        else:
            out.append(x)
    arr = np.array(out)         # <--- OK
    
    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 calling astype(int), we get the error in the title.

    arr = np.array([1, 2], dtype=object)
    arr[:2] = [[10], [20]]
    arr                     # array([list([10]), list([20])], dtype=object)
    
    arr.astype(int)         # <--- ValueError: setting an array element with a sequence.
    

    In this case, convert arr into a list and convert to an ndarray later; or just stack() it.

    np.array(arr.tolist())  # <--- OK
    np.stack(arr)           # <--- OK
    

    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 using astype().

    pandas-case

    In this case, instead of astype(), use stack() or convert to a list and cast to an ndarray.

    import pandas as pd
    
    s = pd.Series([[1,2], [3,4]])
    
    s.astype(int)             # <--- ValueError: setting an array element with a sequence.
    s.to_numpy().astype(int)  # <--- ValueError: setting an array element with a sequence.
    np.array(s.tolist())      # <--- OK
    np.stack(s)               # <--- OK
    
np.where()/np.nonzero() returns a tuple

Another 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 with np.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).

arr = np.array([1, 2, 3])

arr[:3] = np.where(arr>0)       # <--- ValueError: ...
arr[:3] = np.where(arr>0)[0]    # <--- OK
arr[:3] = np.nonzero(arr>0)[0]  # <--- OK
娇女薄笑 2024-10-18 13:56:41

当形状不规则或元素具有不同的数据类型时,传递给np.array的dtype参数只能是object

import numpy as np

# arr1 = np.array([[10, 20.], [30], [40]], dtype=np.float32)  # error
arr2 = np.array([[10, 20.], [30], [40]])  # OK, and the dtype is object
arr3 = np.array([[10, 20.], 'hello'])     # OK, and the dtype is also object

``

When the shape is not regular or the elements have different data types, the dtype argument passed to np.array only can be object.

import numpy as np

# arr1 = np.array([[10, 20.], [30], [40]], dtype=np.float32)  # error
arr2 = np.array([[10, 20.], [30], [40]])  # OK, and the dtype is object
arr3 = np.array([[10, 20.], 'hello'])     # OK, and the dtype is also object

``

熊抱啵儿 2024-10-18 13:56:41

就我而言,我有一个嵌套列表作为我想用作输入的系列。

首先检查:如果

df['nestedList'][0]

输出类似 [1,2,3] 的列表,则您有一个嵌套列表。

然后检查更改为输入 df['nestedList'][0] 时是否仍然出现错误。

那么您的下一步可能是将所有嵌套列表连接到一个非嵌套列表中,使用

[item for sublist in df['nestedList'] for item in sublist]

嵌套列表的扁平化借自 如何从列表列表中制作平面列表?

In my case, I had a nested list as the series that I wanted to use as an input.

First check: If

df['nestedList'][0]

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

[item for sublist in df['nestedList'] for item in sublist]

This flattening of the nested list is borrowed from How to make a flat list out of list of lists?.

我不在是我 2024-10-18 13:56:41

就我而言,这是版本问题。我收到 numpy 版本 = 1.24.1 的错误。但当我降级到1.21.6时,问题就解决了。

python -m pip install numpy==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.

python -m pip install numpy==1.21.6
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文