Home > Blockchain >  How to iterate over single element of numpy array
How to iterate over single element of numpy array

Time:02-03

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. Please tell me. Thanks

I tried arr[0][-10:] but it returned the entire element and not the last 10 elements

CodePudding user response:

You can get what you want by list comprehension.

np.array([item[0][-10:] for item in arr])

CodePudding user response:

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.

CodePudding user response:

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

If this answer gets a downvote again I'd love a comment on what could be improved. Thanks.

  • Related