Find Length of Each String Element in Numpy Array using C++



Here we will see how to get the length of each string element in the Numpy Array. Numpy is a library for Numeric Python, and it has very powerful array class. Using this we can store data in an array like structure. To get the length we can follow two different approach, these are like below −

Example

import numpy as np
str_arr = np.array(['Hello', 'Computer', 'Mobile', 'Language', 'Programming', 'Python'])
print('The array is like: ', str_arr)
len_check = np.vectorize(len)
len_arr = len_check(str_arr)
print('Respective lengts: ', len_arr)

Output

The array is like: ['Hello' 'Computer' 'Mobile' 'Language' 'Programming' 'Python']
Respective lengts: [ 5 8 6 8 11 6]

Another approach using loop

Example

import numpy as np
str_arr = np.array(['Hello', 'Computer', 'Mobile', 'Language', 'Programming', 'Python'])
print('The array is like: ', str_arr)
len_arr = [len(i) for i in str_arr]
print('Respective lengts: ', len_arr)

Output

The array is like: ['Hello' 'Computer' 'Mobile' 'Language' 'Programming' 'Python']
Respective lengts: [5, 8, 6, 8, 11, 6]
Arnab Chakraborty
Arnab Chakraborty

Updated on: 2019-11-04T07:52:59+05:30

133 Views

Kickstart Your Career

Get certified by completing the course

Get Started