ValueError :Setting an array element with a sequence using numpy

匿名 (未验证) 提交于 2019-12-03 09:05:37

问题:

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.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!