Python Shortest String in NumPy Array
To find the shortest string in a given NumPy array, say arr, you can use the min(arr, key=len) function that determines the minimum by comparing the length of the array elements using the len() function as a key for comparison.
import numpy as np arr = np.array(['Alice', 'Bob', 'Carl']) print(min(arr, key=len)) # Bob
You can find more about the powerful min() function in our detailed blog tutorial:
π Recommended Tutorial: Python Minimum Function and NumPy Min and Max on 1D arrays
Python Length of Shortest String in NumPy Array
To find the length of the shortest string in a NumPy array arr, use the min(arr, key=len) function to obtain the string with the minimum length and then pass this min string into the len() function to obtain the number of characters.
len(min(arr, key=len))
Here’s a more detailed code example of a simple 1D NumPy Array:
import numpy as np arr = np.array(['Alice', 'Bob', 'Carl']) # Print Shortest String: print(min(arr, key=len)) # Bob # Print Length of Shortest String print(len(min(arr, key=len))) # 3
Get Shortest String from NumPy Axis (2D, Column or Row)
To get the shortest string from a certain NumPy array axis (e.g., row or column), first use simple NumPy slicing and indexing to get that axis (e.g., arr[0, :] to get the first row) and pass it into the min() function with the key argument set to the length function like so: min(arr[0, :], key=len).
Here’s an example to get the shortest string of the first row of a 2D array:
import numpy as np
arr = np.array([['Alice', 'Bob', 'Carl'],
['Ann', 'Zoe', 'Leonard']])
print(min(arr[0, :], key=len))
# Bob
Here’s an example to get the shortest string of the third column of a 2D array:
print(min(arr[:, 2], key=len)) # Carl
You get the idea. π
If you want to get the shortest string from the whole NumPy array, not only from a column or row or axis, first flatten it and then pass the flattened array into the min() function using the key=len argument.
π Recommended Tutorial: How to Flatten a NumPy Array?
Also, check out our tutorial on finding the maximum string in a NumPy array.