Wrapping a numpy array element to integer - python

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.

Related

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.

Loop through a list in Python using enumerate and openpyxl

New Python convert here. Simply, trying to loop through a list in Python using openpyxl. Of course, my list has about 100 items and my code has more conditions.
lst = ['1','2','a','a12']
for value in enumerate(lst):
row = ws1.iter_rows(min_row=value,max_row=value)
When I try without enumerate I get error "must be str, not int" and when I try with enumerate I get error "Can only concatenate tuple (not "int") to tuple".
I believe it has something to do with min_row and max_row requiring an int, but even then I get "'int' object is not iterable". Also, tried making value str() and int()
Any advice much appreciated, thank you.
When you wrap an iterable with enumerate, you get two values:
the index of enumeration
the value of the iterable at that index
That pair is emitted from enumerate() as a tuple.
You're only identifying one variable name, though, so value contains the whole tuple,
i.e. value = (i, current_val_of_lst).
Instead, try:
lst = ['1','2','a','a12']
for i, value in enumerate(lst):
# i is the enumeration index
# value is the entry in list
...

Finding the index of a header in a structured array for a part of the header name

In my list there are strings such as
A_list= ['mass_32_', 'mass_40_', 'mass_28_']
I want to find the index of an element from an array of just the numbers.
For example
masses=[32,28]
I want to find the index of the ints in masses that correspond to the index in A_list.
Any suggestions of a for/while loop?
Try this:
[A_list.index('mass_{}_'.format(m)) for m in masses]

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

error extracting element from an array. 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.

Categories

Resources