1

If this is the nparray i have

arr_str = np.array(['10', '100', '301', '23423'])

I want to convert into like this using slicing get the last char in the str a[-1] where a is element in nparray

arr_slice = np.array(['0', '0', '1', '3'])

just like how we can add numbers to each element of nparray like

arr_str.asType(int) + 5
abhinit21
  • 330
  • 1
  • 4
  • 13

2 Answers2

4

Why not use a list comprehension?

>>> np.array([x[-1] for x in arr_str])
array(['0', '0', '1', '3'], dtype='<U1')

Alternatively you can use the % modulo operator:

>>> arr_str.astype(int) % 10
array([0, 0, 1, 3])
Ivan
  • 34,531
  • 8
  • 55
  • 100
2

this short answer for you, try this:

np.array(list(map(lambda x : int(x[-1]) , list(arr_str)))) + 5
# array([5, 5, 6, 8])
I'mahdi
  • 23,382
  • 5
  • 22
  • 30