Thanks to visit codestin.com
Credit goes to www.tutorialspoint.com

Numpy char.title() Function



The Numpy char.title() function is used to capitalize the first letter of each word in every string element of an array by converting the rest of the characters in each word to lowercase.

This function is useful for normalizing strings to title case format where each word begins with an uppercase letter followed by lowercase letters. It processes each string element in the array individually making it ideal for preparing textual data for consistent formatting.

Syntax

Following is the syntax of Numpy char.title() function −

numpy.char.title(a)

Parameter

The Numpy char.title() function accepts a single parameter namely, a, which is the input array with strings to be titled.

Return Value

This function returns an array with the same shape as the input, with each word capitalized.

Example 1

Following is the basic example of Numpy char.title() function in which the first element of the given input array each string first letter is capitalized and the rest of the elements changed to lower case −

import numpy as np
arr = np.array(['welcome', 'to', 'tutorialspoint', 'happy learning'])
titled_arr = np.char.title(arr)
print(titled_arr)

Below is the output of the basic example of numpy.char.title() function −

['Welcome' 'To' 'Tutorialspoint' 'Happy Learning']

Example 2

With the help of title() function we can convert the first letter of each word in a string to uppercase and the remaining letters to lowercase by making it useful for normalizing strings with mixed cases −

import numpy as np

arr = np.array(['hElLo', 'wOrLd'])
titled_arr = np.char.title(arr)
print(titled_arr)

Here is the output of the above example −

['Hello' 'World']

Example 3

We can capitalize the first letter of each word in strings within a multi-dimensional NumPy arrays. Here is the example we are converting the 2d array string elements into title case −

import numpy as np

arr = np.array([['hello world', 'good morning'], ['goodbye everyone', 'have a nice day']])
title_arr = np.char.title(arr)
print(title_arr)

Below is the output of applying title() function to 2d array −

[['Hello World' 'Good Morning']
 ['Goodbye Everyone' 'Have A Nice Day']]
numpy_string_functions.htm
Advertisements