3

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.

11
  • 1
    What does ptemperature do? Commented May 20, 2017 at 11:48
  • 1
    Based on the error, it looks that p_temperator does not return a scalar, but a numpy array itself. Commented May 20, 2017 at 11:48
  • @WillemVanOnsem - it just returns a number given two inputs p and temp
    – gansub
    Commented May 20, 2017 at 11:49
  • 1
    In the question. But please, just a sample (for example 5x5 not full 181x360), basically enough for us to reproduce your problem and help you solved it
    – Nuageux
    Commented May 20, 2017 at 12:04
  • 1
    @ADITYA No, that throws an ValueError: could not convert string to float: exception. :)
    – MSeifert
    Commented May 20, 2017 at 15:50

1 Answer 1

5

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.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.