Sunday, September 8, 2024
HomePythonDiscover the Longest String in a NumPy Array? – Finxter

Discover the Longest String in a NumPy Array? – Finxter


Python Longest String in NumPy Array

To seek out the longest string in a given NumPy array, say arr, you should utilize the max(arr, key=len) perform that determines the utmost by evaluating the size of the array components utilizing the len() perform as a key for comparability.

import numpy as np

arr = np.array(['Alice', 'Bob', 'Carl'])
print(max(arr, key=len))
# Alice

You’ll find extra concerning the highly effective max() perform in our detailed weblog tutorial:

👉 Beneficial Tutorial: Python Most Perform

Python Size of Longest String in NumPy Array

To seek out the size of the longest string in a NumPy array arr, use the max(arr, key=len) perform to acquire the string with the utmost size after which move this max string into the len() perform to acquire the variety of characters of the max string.

len(max(arr, key=len))

Right here’s a extra detailed code instance of a easy 1D NumPy Array:

import numpy as np

arr = np.array(['Alice', 'Bob', 'Carl'])

# Print Longest String:
print(max(arr, key=len))
# Alice

# Print Size of Longest String
print(len(max(arr, key=len)))
# 5

Get Longest String from NumPy Axis (2D, Column or Row)

To get the longest string from a sure NumPy array axis (e.g., row or column), first use easy NumPy slicing and indexing to get that axis (e.g., arr[0, :] to get the primary row) and move it into the max() perform with the key argument set to the size perform like so: max(arr[0, :], key=len).

Right here’s an instance to get the longest string of the first row of a 2D array:

import numpy as np

arr = np.array([['Alice', 'Bob', 'Carl'],
                ['Ann', 'Zoe', 'Leonard']])


print(max(arr[0, :], key=len))
# Alice

Right here’s an instance to get the longest string of the third column of a 2D array:

print(max(arr[:, 2], key=len))
# Leonard

You get the concept. 🙂

If you wish to get the longest string from the entire NumPy array, not solely from a column or row or axis, first flatten it after which move the flattened array into the max() perform utilizing the key=len argument.

👉 Beneficial Tutorial: Flatten a NumPy Array?

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments