NumPy strings.upper()
The numpy.strings.upper()
function converts each string element in an input array to uppercase, applying the Python str.upper()
method element-wise.
Syntax
</>
Copy
numpy.strings.upper(a)
Parameters
Parameter | Type | Description |
---|---|---|
a | array-like | Input array containing string elements. Can have StringDType , bytes_ , or str_ dtype. |
Return Value
Returns an array with the same shape as the input, where all string elements have been converted to uppercase.
Examples
1. Converting a Single String to Uppercase
Here, we convert a single string to uppercase using NumPy.
</>
Copy
import numpy as np
# Define a single string as a NumPy array
word = np.array("apple", dtype="U")
# Convert to uppercase
result = np.strings.upper(word)
# Print the result
print("Uppercase string:", result)
Output:
Uppercase string: APPLE

2. Converting an Array of Strings to Uppercase
We apply numpy.strings.upper()
to an array of multiple words.
</>
Copy
import numpy as np
# Define an array of strings
words = np.array(["apple", "banana", "cherry"], dtype="U")
# Convert each element to uppercase
uppercase_words = np.strings.upper(words)
# Print the result
print("Original words:", words)
print("Uppercase words:", uppercase_words)
Output:
Original words: ['apple' 'banana' 'cherry']
Uppercase words: ['APPLE' 'BANANA' 'CHERRY']

3. Using Uppercase Conversion with Byte Strings
NumPy also allows the conversion of byte strings to uppercase.
</>
Copy
import numpy as np
# Define an array of byte strings
byte_words = np.array([b"grape", b"mango"], dtype="S")
# Convert byte strings to uppercase
uppercase_byte_words = np.strings.upper(byte_words)
# Print the result
print("Original byte words:", byte_words)
print("Uppercase byte words:", uppercase_byte_words)
Output:
Original byte words: [b'grape' b'mango']
Uppercase byte words: [b'GRAPE' b'MANGO']

4. Converting Strings in a Structured NumPy Array
Using numpy.strings.upper()
on a structured array with string fields.
</>
Copy
import numpy as np
# Define a structured array with string fields
dtype = [("fruit", "U10"), ("color", "U10")]
data = np.array([("apple", "red"), ("banana", "yellow")], dtype=dtype)
# Convert only the 'fruit' field to uppercase
data["fruit"] = np.strings.upper(data["fruit"])
# Print the result
print("Structured array with uppercase fruits:")
print(data)
Output:
Structured array with uppercase fruits:
[('APPLE', 'red') ('BANANA', 'yellow')]

Only the fruit
field is modified, while the color
field remains unchanged.