ValueError :Setting an array element with a sequen

2019-05-10 00:12发布

问题:

I have this piece of code in python

data = np.empty(temp.shape)
maxlat = temp.shape[0]
maxlon = temp.shape[1]
print(maxlat,maxlon)

for i in range(0,maxlat) :
    for j in range(0,maxlon):
        data[i][j] = p_temperature(pr,temp[i][j])

When I run this code in Python 3.5, I get this error

ValueError : setting an array element with a sequence

The value of maxlat is 181 and the value of maxlon is 360.

The shape of temp array is (181,360)

I also tried the suggestion in the comments:

for i in range(0,maxlat) :
    for j in range(0,maxlon):
        data[i][j] = temp[i][j]

But I get the same error.

回答1:

Based on the exception you get it seems likely that temp is an object array containing sequences. You could simply use numpy.empty_like:

data = np.empty_like(temp)  # instead of "data = np.empty(temp.shape)"

This creates a new empty array with the same shape and dtype - like your original array.


For example:

import numpy as np

temp = np.empty((181, 360), dtype=object)
for i in range(maxlat) :
    for j in range(maxlon):
        temp[i][j] = [1, 2, 3]

With the new approach it works:

data = np.empty_like(temp)
maxlat = temp.shape[0]
maxlon = temp.shape[1]
print(maxlat, maxlon)

for i in range(maxlat) :
    for j in range(maxlon):
        data[i][j] = temp[i][j]

And this temp array also reproduces the exception on your original code sample:

data = np.empty(temp.shape)  # your approach
maxlat = temp.shape[0]
maxlon = temp.shape[1]
print(maxlat, maxlon)

for i in range(maxlat) :
    for j in range(maxlon):
        data[i][j] = temp[i][j]

throws the exception:

ValueError: setting an array element with a sequence.