How to iterate over single element of numpy array - python

I have a numpy array of shape (100, 1), having all elements similar to as shown below
arr[0] = array(['37107287533902102798797998220837590246510135740250'], dtype=object)
I need to iterate over this single element of array and get the last 10 elements of it. I have not been able to find out how to iterate over single element.
I tried arr[0][-10:] but it returned the entire element and not the last 10 elements

You can get what you want by list comprehension.
np.array([item[0][-10:] for item in arr])

If arr.shape is (100,1), then arr[0].shape is (1,), which is shown array(['astring']) brackets.
arr[0,0] should be a string, e.g. '37107287533902102798797998220837590246510135740250'
Strings take slice indexing, eg. arr[0,0][-10:]
arr[0][0] also works to get one string, but the [0,0] syntax is better.
It isn't clear at what level you want to iterate, since just getting the last 10 characters of one of the string elements doesn't need iteration.
Anyways, pay attention to what each level of indexing is producing, whether it be another array, a list, or a string. Indexing rules for these different classes are similar, but different in important ways.

# import numpy
import numpy as np
arr = np.array(['37107287533902102798797998220837590246510135740250'], dtype=object)
# print the last 10 elements of the array
print(arr[0][-10:])
# iterate through the array and print the elements in reverse order
for i in arr[0][::-1]:
print(i)
# iterate through the array and print the last 10 elements in reverse order
for i in arr[0][-10:][::-1]:
print(I)
# iterate through the array and print the last 10 elements in forward order
for i in arr[0][-10:]:
print(i)
#hpaulj makes a good point. My original answer works with numpy as requested but I didn't really leave the OP an explanation. Using his string advice this how I would do it if it was a string and I wanted to iterate for some reason:
s1 = '37107287533902102798797998220837590246510135740250'
result = 0
for x in s1[-10:]:
print(x)
result += int(x)
print(result)

Related

How to print specific range of values in a 1 dimensional array in Python?

Given the array below:
array= [1,2,3,4,5,6,7,8]
Using Python, how to print the 3rd to the 6th element of the array?
ie:
3, 4, 5, 6
You can use python list slices to get the desired set of numbers, so in your case, you can do the next:
a = array[2:6]
Now you have the items that you want in the array and print them as you like, printing the full array or printing them one by one iterating over the array. Even you can print them directly with:
print(array[2:6])

How to index two elements from a Python list?

How come I can't index a Python list for multiple out-of-sequence index positions?
mylist = ['apple','guitar','shirt']
It's easy enough to get one element, but not more than one.
mylist[0] returns 'apple', but mylist[0,2] returns TypeError: list indices must be integers or slices, not tuple
So far, only this seems to work which looks hectic:
np.asarray(mylist)[[0,2]].tolist()
Use Extended Slices:
mylist = ['apple','guitar','shirt']
print(mylist[::2])
#Output: ['apple', 'shirt']
Use list comprehension:
print([mylist[i] for i in [0, 2]])
# ['apple', 'shirt']
Or use numpy.array:
import numpy as np
print(np.array(mylist)[[0, 2]])
# ['apple', 'shirt']
Python list supports only integer and slice for indices. The standard slicing rule of python is as follow:
i:j:k inside the square bracket for accessing more than one element.
where i is the starting index, j is the ending index and k is the steps.
>>> list_ = ['apple','guitar','shirt']
>>> mylist[0:2]
['apple', 'guitar']
if you want some random element as per some certain indices then use List Comprehension or just a for loop
There is an another way for accessing items from certain indices by using map() function.
>>> a_list = [1, 2, 3]
>>> indices_to_access = [0, 2]
>>> accessed_mapping = map(a_list.__getitem__, indices_to_access)
>>> accessed_list = list(accessed_mapping)
>>> accessed_list
[ 1, 3]
A recommendation from me would be: use the NumPy library (import numpy as np). It will allow you to create a numpy array which has advantages over a standard list. Using the numpy array, you will be able to access as many items as you would like through a process called Fancy Indexing.
mylist[0] returns 'apple'
The above code/statement which was available in the question description depicts a Python programmer performing indexing- which is the process of passing the index position of a sinlge item in order to retrieve the item- However in the event of requiring multiple items, that would be difficult/not possible.
import numpy as np #import the numpy package
mylist = np.array(['apple','guitar','shirt']) #create the numpy array
mylist[[0,2]] #return the first and third items ONLY. (zero-indexed)
Out[11]: array(['apple', 'shirt'], dtype='<U6')
If you were to make use of the NumPy library in python (looking above), you would be able to create a NumPy array, which allows for more methods and operations to be performed on your array.
As compared to mylist[0] which returns a single/individual item only, Using mylist[[0,2]] we specify to the python compiler that we wish to retrieve exactly two elements from our list, and those elements are located at index positions '0' and '2'. (zero-indexed). Notice that we passed in the index positions of the desired elements in a list. Therefore instead of returning one element, we return two (or as many as you would like).

how to efficiently link lines of numpy array to sets of tags?

I am trying to convert a list of data structure, all of the same type, into a numpy arrays. It works well for all the number attributes but there is one attribute whose value is a set of tags (strings). And I don't see how to model that properly with numpy .
So far, I use a 2d array. Each row contains the attributes of one data structure, one per columns. But for the set of strings, I don't know how to use that in a numpy array.
It seems that I can put a set as the value for a cell in the array but It seems to break the point of numpy : fixed size arrays with efficient functions that apply on them.
Any idea ?
I think the best alternative is to use a list of tuples
Supposing l is your list:
In [1]: l = [[4,5,6,'a','b'],['x','y',2,3]]
In [2]: _l = [tuple(elem) for elem in l]
In [3]: _l
Out[1]: [(4, 5, 6, 'a', 'b'), ('x', 'y', 2, 3)]
Alternatively you could create a list of tuple where the first element of the tuple is the numpy array, and the second element is the tag.

Append to Numpy Using a For Loop

I am working on a Python script that takes live streaming data and appends it to a numpy array. However I noticed that if I append to four different arrays one by one it works. For example:
openBidArray = np.append(openBidArray, bidPrice)
highBidArray = np.append(highBidArray, bidPrice)
lowBidArray = np.append(lowBidArray, bidPrice)
closeBidArray = np.append(closeBidArray, bidPrice)
However If I do the following it does not work:
arrays = ["openBidArray", "highBidArray", "lowBidArray", "closeBidArray"]
for array in arrays:
array = np.append(array, bidPrice)
Any idea on why that is?
Do this instead:
arrays = [openBidArray, highBidArray, lowBidArray, closeBidArray]
In other words, your list should be a list of arrays, not a list of strings that coincidentally contain the names of arrays you happen to have defined.
Your next problem is that np.append() returns a copy of the array with the item appended, rather than appending in place. You store this result in array, but array will be assigned the next item from the list on the next iteration, and the modified array will be lost (except for the last one, of course, which will be in array at the end of the loop). So you will want to store each modified array back into the list. To do that, you need to know what slot it came from, which you can get using enumerate().
for i, array in enumerate(arrays):
arrays[i] = np.append(array, bidPrice)
Now of course this doesn't update your original variables, openBidArray and so on. You could do this after the loop using unpacking:
openBidArray, highBidArray, lowBidArray, closeBidArray = arrays
But at some point it just makes more sense to store the arrays in a list (or a dictionary if you need to access them by name) to begin with and not use the separate variables.
N.B. if you used regular Python lists here instead of NumPy arrays, some of these issues would go away. append() on lists is an in-place operation, so you wouldn't have to store the modified array back into the list or unpack to the individual variables. It might be feasible to do all the appending with lists and then convert them to arrays afterward, if you really need NumPy functionality on them.
In your second example, you have strings, not np.array objects. You are trying to append a number(?) to a string.
The string "openBidArray" doesn't hold any link to an array called openBidArray.

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

Categories

Resources