w3resource

NumPy: Create an array of zeros and three column types


Zeros Array with Multiple Column Types

Write a NumPy program to create an array of zeros and three column types (integer, floating, and character).

Sample Solution:

Python Code:

# Importing the NumPy library and aliasing it as 'np'
import numpy as np

# Creating a NumPy array 'x' filled with zeros, with a structured data type
# The dtype specifies a structure containing an integer, a floating-point number, and a string of specific lengths
x = np.zeros((3,), dtype=('i4,f4,a40'))

# Creating a list 'new_data' containing tuples with structured data: integer, float, and string
new_data = [(1, 2., "Albert Einstein"), (2, 2., "Edmond Halley"), (3, 3., "Gertrude B. Elion")]

# Assigning the 'new_data' list to the array 'x', filling the array with the provided structured data
x[:] = new_data

# Printing the resulting array 'x' with structured data
print(x) 

Sample Output:

[(1,  2., b'Albert Einstein') (2,  2., b'Edmond Halley')               
 (3,  3., b'Gertrude B. Elion')]

Explanation:

In the above code:

‘np.zeros((3,), dtype=('i4,f4,a40'))’ creates a structured 1D NumPy array x with 3 elements. Each element has a composite data type consisting of three fields: an int32 ('i4'), a float32 ('f4'), and a fixed-length string with 40 characters ('a40').

new_data = [(1, 2., "Albert Einstein"), (2, 2., "Edmond Halley"), (3, 3., "Gertrude B. Elion")]: This code defines a list of tuples named new_data, which contains three tuples. Each tuple has three elements, corresponding to the structure of the array x.

x[:] = new_data: This line assigns the values from new_data to the structured array x. The slice [:] ensures that all elements of x are replaced with the corresponding elements from new_data.

print(x): Finally printf() function prints the resulting structured array ‘x’.

Python-Numpy Code Editor: