How to create NumPy array in python

Photo by Christina Morillo from Pexels

Today, I will show you how to use the NumPy array with the following example.

create one-dimension NumPy array

import numpy as np
arr = np.array([1, 2, 3])
print(arr)
# Output
# [1 2 3]

create two-dimension NumPy array

import numpy as np
arr = np.array([[1, 1, 1], [2, 2, 2]])
print(arr)
# Output
# [[1 1 1]
# [2 2 2]]

Set minimum dimension to NumPy array

import numpy as np
arr = np.array([1, 1, 1], ndmin=3)
print(arr)
# Ouput
# [[[1 1 1]]]

Numpy can automatically upcasting type like this

import numpy as np
arr = np.array([1, 1, 1.0])
print(arr)
# Output
# [1. 1. 1.]

also can change the data type in an array like this

import numpy as np
arr = np.array([1, 1, 1], dtype=float)
print(arr)
# Output
# [1. 1. 1.]

Thank you for reading & enjoy your coding 🙂

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s