error extracting element from an array. python - python

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

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.

Related

How to create a new numpy array filled with empty lists?

I want to generate a numpy array filled empty lists. I tried this:
import numpy as np
arr=np.full(6, fill_value=[], dtype=object)
And I got an error:
ValueError: could not broadcast input array from shape (0) into shape (6)
But if I use:
arr = np.empty(6, dtype=object)
arr.fill([])
It is ok. Why does numpy.full not work here? What is the right way to initialize an array filled with empty lists?
The reason you can't use fill_value=[] is hidden in the docs:
In the docs, it says that np.full's fill_value argument is either a scalar or array-like. In the docs for np.asarray, you can find their definition of array-like:
Input data, in any form that can be converted to an array. This includes lists, lists of tuples, tuples, tuples of tuples, tuples of lists and ndarrays.
So, lists are treated specially as "array" fill types and not scalars, which is not what you want. Additionally, arr.fill([]) is actually not what you want, since it fills every element to the same list, which means appending to one appends to all of them. To circumvent this, you can do that this answer states, and just initialize the array with a list:
arr = np.empty(6, dtype=object)
arr[...] = [[] for _ in range(arr.shape[0])]
which will create an array with 6 unique lists, such that appending to one does not append to all of them.
You can try to use numpy.empty(shape, dtype=float, order='C')

What is dtype with more than one element in ndarray of numpy?

x = np.array([(1,2),(3,4)],dtype=[('a','<i4'),('b','<i4')])
Why do we use the dtype with more than one elements in ndarray and how is it useful? How do we interpret this?
First of all, you should notice that this array would only have one dimension which is represented by the dtype
('a','<i4'),('b','<i4')
The way I like to think about this is that we are creating a dtype by concatenating other dtypes together. We treat each pair of tuples as a single element of our array, with individual specs for each element of each tuple.
In other words, the dtype really just signifies the structure of the elements.
To learn more, see this

dtype of ndarray containing string in python

I know that in case of ndarray containing strings, dtype returned will be of the form dtype(S#) where # denotes the length of the string.
As shown in figure the array 'a' which is generated from a list [1,'2','3']. Once the array is created all the elements become string type. Array 'b' is created from a list ['1',2,'3'].
a.dtype gives S21 while b.dtype gives S1. Length of elements in both a and b is 1. Why the length of elements in first array is taken as 21 even though all the elements have length 1?
It is found that dtype will continue to be 'S21' even if 1 is replaced with 9223372036854775807. Once we use 9223372036854775808, dtype becomes 'S20'. How does this happen
Somebody please explain
np.array is compiled code, so we'd have to dig into that to see exactly what is going on. I don't recall seeing any documentation. So the easiest thing is to just try some values and look for a pattern.
If the 1st element is a string it appears to use the longest string (or str(i) for numbers).
If the 1st is a number it appears to start with some default size.
Unless the dtype is truncating some of the strings, I wouldn't worry too much about this behavior. If it matters, I'd suggest defining your own length.

Convert array element to float

I have a one dimensional array called monteCarloPerf which can look something like:
monteCarloPerf [[113.4848779294831], [169.65800173373898], [211.35999049731927], [169.65800173373901], [229.66974328119005]]
I am retrieving a single element from the array using:
finalValue = monteCarloPerf[arrayValue]
where arrayValue is an integer.
Say arrayValue = 0, at the moment I am getting returned : [113.4848779294831]. Is there a way to just return the float without the brackets please? So I would be returned just 113.4848779294831.
Many thanks
Your object monteCarloPerf is a one dimensional array containing elements of one dimensional arrays, or a list of lists. In order to access the value of the first element of the object you have to change your access to that element to the following:
finalValue = monteCarloPerf[arrayValue][0]
In fact, that is a 'TWO dimensional' array.
To get the float value you can do the following:
finalValue = monteCarloPerf[arrayValue][0]
Or you can transform the two dimensional array to a one dimensional array:
one_dim = [item[0] for item in monteCarloPerf]
I hope this helps.
monteCarloPerf is a list of list. When you are using monteCarloPerf[index] it is returning list at index position. Based on the symmetry in your list, in each sub-list, item at [0] position is the actual value you are trying to fetch.
Use this to fetch the value
finalValue = monteCarloPerf[arrayValue][0]
Here's a weird way to do this without using list.__getitem__() method:
float(''.join(i for i in str(monteCarloPerf[arrayValue])))

Wrapping a numpy array element to integer

I have a list of subgraphs that I am attempting to access within a loop:
index=[5,3,4,1,1,3,4,2,3,4,2,2,3,3,2,4]
subgraph=[[subgraph1],[subgraph2],[subgraph3],[subgraph4],[subgraph5]]
for i in range(len(index)):
for j in range(i+1,len(index)):
if index[j]==index[i]
continue
testgraphi=copy.copy(subgraph[index[i]])
testgraphj=copy.copy(subgraph[index[j]])
so in the first loop through, testgraphi would be assigned subgraph5, and testgraphj would be assigned subgraph3. However, when I attempt this method, I am returned an error list indices must be integers, not numpy.float64. Which is logical, because index is ACTUALLY initialized as a numpy array in the full span of my program(and it must stay this way). So my question is, how can I cast this value so that it can be used as an index for my subgraph list? So that when testgraph is initialized, it will retrieve the value of index at which the loop is at, and use this to define which list index to return?
You can convert numpy.float64 to float by doing this: var.item(). Then convert it into an integer so you can use it as your index: int(var.item())
you could try this:
new_index = np.asarray(index, dtype=np.int32)
This should cast all values in index into integer.

Categories

Resources