ValueError:使用numpy使用序列设置数组元素 [英] ValueError :Setting an array element with a sequence using numpy

查看:86
本文介绍了ValueError:使用numpy使用序列设置数组元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在python中有这段代码

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])

当我在Python 3.5中运行此代码时,出现此错误

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

ValueError : setting an array element with a sequence

maxlat的值是181maxlon的值是360.

temp数组的形状为(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.

推荐答案

基于例外情况,您可能会发现temp是包含序列的object数组.您可以简单地使用 numpy.empty_like :

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)"

这将创建一个具有相同形状和dtype的新空数组-与原始数组 like 类似.

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

例如:

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]

temp数组还会在原始代码示例中重现异常:

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]

引发异常:

ValueError:设置具有序列的数组元素.

ValueError: setting an array element with a sequence.

这篇关于ValueError:使用numpy使用序列设置数组元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆