w3resource

NumPy: Add two zeros to the beginning of each element of a given array of string values


Write a NumPy program to add two zeros to the beginning of each element of a given array of string values.

Sample Solution:

Python Code:

# Importing necessary library
import numpy as np 

# Creating a NumPy array containing strings
nums = np.array(['1.12', '2.23', '3.71', '4.23', '5.11'], dtype=np.str)

# Displaying the content of the original array
print("Original array:")
print(nums)

# Adding two zeros to the beginning of each element of the array using np.char.add()
print("\nAdd two zeros to the beginning of each element of the said array:")
print(np.char.add('00', nums))

# Another method to add zeros to the beginning of each element using np.char.rjust()
print("\nAlternate method:")
print(np.char.rjust(nums, 6, fillchar='0')) 

Sample Output:

Original array:
['1.12' '2.23' '3.71' '4.23' '5.11']

Add two zeros to the beginning of each element of the said array:
['001.12' '002.23' '003.71' '004.23' '005.11']

Alternate method:
['001.12' '002.23' '003.71' '004.23' '005.11']

Explanation:

In the above code –

nums = np.array(['1.12', '2.23', '3.71', '4.23', '5.11'], dtype=np.str): This line creates a NumPy array of strings called nums with 5 elements.

np.char.add('00', nums): This line uses the add function from the np.char module to concatenate the string '00' to each element in the nums array.

np.char.rjust(nums, 6, fillchar='0'): This line uses the rjust() function from the np.char module to right justify each element in the nums array with a total width of 6 characters. The fillchar parameter is set to '0', which means that any empty space to the left of the string will be filled with zeroes.

Python-Numpy Code Editor: