本文介绍了错误从数组中提取元素. Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类似这样的numpy数组

I have a numpy array something like this

a = np.array(1)

现在,如果我想从该数组中取回1.我该如何退缩?

Now if I want to get 1 back from this array. how do i retreive this??

我尝试过

a[0], a(0).. 

喜欢

IndexError: 0-d arrays can't be indexed

TypeError: 'numpy.ndarray' object is not callable

我什至试图做一些奇怪的拼合和填充,但是我很确定它不应该那么复杂.而且我都出错了..我想要的只是那个1作为整数吗?谢谢

I even tried to do some weird flattening and stuff but I am pretty sure that it shouldnt be that complicated.. And i am getting errors in both.. all i want is that 1 as an int?Thanks

推荐答案

您创建的内容

a = np.array(1)

是一个零维数组,无法对其进行索引.您也不需要 对其建立索引-您可以直接使用a,就好像它是标量值一样.如果确实需要其他类型的值,例如float,则可以使用float(a)显式转换它.如果需要数组的基本类型,则可以使用a.item()a[()].

is a zero-dimensional array, and these cannot be indexed. You also don't need to index it -- you can use a directly as if it were a scalar value. If you really need the value in a different type, say float, you can explicitly convert it with float(a). If you need it in the base type of the array, you can use a.item() or a[()].

请注意,零维数组是可变.如果更改数组中单个条目的值,则可以通过对所存储数组的所有引用来看到该值.如果要存储不可变值,请使用a.item().

Note that the zero-dimensional array is mutable. If you change the value of the single entry in the array, this will be visible via all references to the array you stored. Use a.item() if you want to store an immutable value.

如果您想要一个带有单个元素的一维数组,请使用

If you want a one-dimensional array with a single element instead, use

a = np.array([1])

您现在可以使用a[0]访问单个元素.

You can access the single element with a[0] now.

这篇关于错误从数组中提取元素. Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 05:33