Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

error extracting element from an array. python

Tags:

python

numpy

I have a numpy array something like this

a = np.array(1) 

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

I have tried

a[0], a(0)..  

like

IndexError: 0-d arrays can't be indexed 

or

TypeError: 'numpy.ndarray' object is not callable 

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

like image 860
frazman Avatar asked Mar 21 '12 23:03

frazman


People also ask

What is a 0 dimensional array in Python?

Zero dimensional array is mutable. It has shape = () and dimensional =0. let us do this with the help of example. import numpy as np a = np.array(1) print("Printing the shape of numpy array") print(a.shape) print("printing the dimension of numpy array") print(a.ndim)

What is numpy take?

The numpy take() function takes elements from an array along an axis. The take() function does the same thing as “fancy” indexing (indexing arrays using arrays); however, it can be easier to use if you need items along the given axis.


1 Answers

What you create with

a = np.array(1) 

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[()].

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

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

like image 155
Sven Marnach Avatar answered Sep 19 '22 22:09

Sven Marnach