Skip to content

NumPy - String Functions

NumPy provides a set of vectorized string operations within the numpy.char module. These functions allow you to apply standard string manipulations element-wise to NumPy arrays of string or Unicode data types (numpy.str_, numpy.bytes_, or object arrays containing Python strings).

These functions mirror the behavior of Python’s built-in string methods but operate on entire arrays efficiently. However, it’s worth noting that for complex text processing tasks, libraries like Pandas (with its Series string methods) or native Python list comprehensions combined with standard string methods might offer more flexibility or sometimes better performance.

The numpy.char functions are particularly useful when you already have string data in a NumPy array and need to perform simple, element-wise transformations.

Here’s a summary of some common functions available in numpy.char:

FunctionDescription
add()Element-wise string concatenation for two arrays.
multiply()Element-wise string repetition.
center()Centers each element within a string of specified width.
capitalize()Capitalizes the first character of each element.
title()Title-cases each element (first character of each word capitalized).
lower()Converts each element to lowercase.
upper()Converts each element to uppercase.
split()Splits each element into a list of strings based on a delimiter.
splitlines()Splits each element into a list of lines based on line breaks.
strip()Removes leading/trailing whitespace (or specified characters) from each element.
join()Concatenates elements of a sequence using a specified separator for each element.
replace()Replaces occurrences of a substring with a new string in each element.
decode()Element-wise decoding (e.g., from bytes to strings) using a specified encoding. Requires a bytes array.
encode()Element-wise encoding (e.g., from strings to bytes) using a specified encoding. Requires a string array.

Example Usage:

import numpy as np
str_array = np.array([' hello ', ' world '], dtype=np.str_)
# Strip whitespace
stripped = np.char.strip(str_array)
print(f"Stripped: {stripped}")
# Convert to uppercase
upper_case = np.char.upper(stripped)
print(f"Uppercase: {upper_case}")
# Concatenate with another array
array2 = np.array([' numpy', '!'], dtype=np.str_)
added = np.char.add(upper_case, array2)
print(f"Added: {added}")

Output:

Stripped: ['hello' 'world']
Uppercase: ['HELLO' 'WORLD']
Added: ['HELLO numpy' 'WORLD!']

While NumPy can handle arrays of strings (dtype=str or dtype=object), remember that its core strengths lie in numerical computation. For extensive text manipulation, consider leveraging tools specifically designed for that purpose.

Explore the full list and details in the numpy.char documentation.