Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] How to Find the Longest String in a NumPy Array?
1
How to Find the Longest String in a NumPy Array?

5/5 – (1 vote)

Python Longest String in NumPy Array

To find the longest string in a given NumPy array, say
Code:
arr
, you can use the
Code:
max(arr, key=len)
function that determines the maximum by comparing the length of the array elements using the
Code:
len()
function as a key for comparison.

Code:
import numpy as np arr = np.array(['Alice', 'Bob', 'Carl']) print(max(arr, key=len)) # Alice

You can find more about the powerful
Code:
max()
function in our detailed blog tutorial:

[Image: 1f449.png] Recommended Tutorial: Python Maximum Function

Python Length of Longest String in NumPy Array

To find the length of the longest string in a NumPy array
Code:
arr
, use the
Code:
max(arr, key=len)
function to obtain the string with the maximum length and then pass this max string into the
Code:
len()
function to obtain the number of characters of the max string.

Code:
len(max(arr, key=len))

Here’s a more detailed code example of a simple 1D NumPy Array:

Code:
import numpy as np arr = np.array(['Alice', 'Bob', 'Carl']) # Print Longest String: print(max(arr, key=len)) # Alice # Print Length 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 certain NumPy array axis (e.g., row or column), first use simple NumPy slicing and indexing to get that axis (e.g.,
Code:
arr[0, :]
to get the first row) and pass it into the
Code:
max()
function with the
Code:
key
argument set to the length function like so:
Code:
max(arr[0, :], key=len)
.

Here’s an example to get the longest string of the first row of a 2D array:

Code:
import numpy as np arr = np.array([['Alice', 'Bob', 'Carl'], ['Ann', 'Zoe', 'Leonard']]) print(max(arr[0, :], key=len)) # Alice

Here’s an example to get the longest string of the third column of a 2D array:

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

You get the idea. [Image: 1f642.png]

If you want to get the longest 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
Code:
max()
function using the
Code:
key=len
argument.

[Image: 1f449.png] Recommended Tutorial: How to Flatten a NumPy Array?
Reply

Users browsing this thread:
1 Guest(s)


Forum Jump: