我在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])
当我在 Python 3.5 中运行此代码时,出现此错误
ValueError : setting an array element with a sequence
maxlat
的值为181
,maxlon
的值为360
。
temp
数组的形状是(181,360)
我也尝试了评论中的建议:
for i in range(0,maxlat) :
for j in range(0,maxlon):
data[i][j] = temp[i][j]
但我得到了同样的错误。
最佳答案
根据您得到的异常,temp
似乎是一个包含序列的 object
数组。你可以简单地使用 numpy.empty_like
:
data = np.empty_like(temp) # instead of "data = np.empty(temp.shape)"
这将创建一个具有相同形状和 dtype 的新空数组 - 就像您的原始数组。
例如:
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]
通过新方法,它起作用了:
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]
并且此 temp
数组还会在您的原始代码示例中重现异常:
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]
抛出异常:
ValueError: setting an array element with a sequence.
关于python - 值错误 :Setting an array element with a sequence using numpy,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44085495/