Find the length of each string element in the Numpy array

NumPy builds on (and is a successor to) the successful Numeric array object. Its goal is to create the corner-stone for a useful environment for scientific computing. NumPy provides two fundamental objects: an N-dimensional array object (ndarray) and a universal function object (ufunc).

In this post we are going to discuss ways in which we can find the length of each string element in the given numpy array.

Problem #1 : Given a numpy array whose underlying data is of string type. Find the length of each element in the given object.



Solution : We are going to use numpy.vectorize() function to find the length of each element in the given numpy array object.

filter_none

edit
close

play_arrow

link
brightness_4
code

# importing the numpy library as np
import numpy as np
  
# Create a numpy array
arr = np.array(['New York', 'Lisbon', 'Beijing', 'Quebec'])
  
# Print the array
print(arr)

chevron_right


Output :

Now we will use numpy.vectorize() function to find the length of each element in the given numpy array object.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Use vectorize function of numpy
length_checker = np.vectorize(len)
  
# Find the length of each element
arr_len = length_checker(arr)
  
# Print the length of each element
print(arr_len)

chevron_right


Output :

As we can see in the output, we have successfully calculated the length of each string element in the given numpy array object.

Problem #2 : Given a numpy array whose underlying data is of string type. Find the length of each element in the given object.

Solution : We are going to use List comprehension technique to find the length of each element in the given numpy array object.

filter_none

edit
close

play_arrow

link
brightness_4
code

# importing the numpy library as np
import numpy as np
  
# Create a numpy array
arr = np.array(['New York', 'Lisbon', 'Beijing', 'Quebec'])
  
# Print the array
print(arr)

chevron_right


Output :


Now we will use List comprehension technique to find the length of each element in the given numpy array object.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Find the length of each element
arr_len = [len(i) for i in arr]
  
# Print the length of each element
print(arr_len)

chevron_right


Output :

As we can see in the output, we have successfully calculated the length of each string element in the given numpy array object.



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.