Trusted answers to developer questions

How to create an array in NumPy

Get Started With Machine Learning

Learn the fundamentals of Machine Learning with this free course. Future-proof your career by adding ML skills to your toolkit — or prepare to land a job in AI or Data Science.

NumPy arrays are the basis of all computations performed by the NumPy library. They are simple Python lists with a few additional properties. A NumPy array has the dtype attribute, which specifies the data type of all the elements in the array.

If the array contains elements of different data types, all the elements are cast into the largest type (a process known as upcasting). A NumPy array can also be a copy or a reference to an existing NumPy array.

import numpy as np
# A 2D array
arr1 = np.array([[10, 20, 30], [-4, -5, -6]],
dtype = np.double) # All the elements are doubles
print("2D NumPy array of doubles \n" + repr(arr1) + "\n")
arr2 = np.array([10, 'hello', 5.8],
dtype = np.str) # All the elements are strings
print("1D NumPy array of string \n" + repr(arr2) + "\n")
# Creating a reference to a NumPy array
arr3 = arr2
arr3[0] = 50
print("The new value of arr2[0]: " + arr2[0])
# Creating a Copy
arr4 = arr2.copy()
arr4[0] = '100' # arr2 will not be affected
print("The value of arr2[0] is not altered: " + arr2[0])
# Assigning an empty value to an index
arr4[2] = np.nan
print("Assigning NaN to an index: " + arr4[2])

Creating array data

When working with large amounts of data, hardcoding an array isn’t always possible. We can use the arange method. It can take up to 3 parameters which will indicate the nature of the data:

import numpy as np
# Creating an array from 0 to 9
arr = np.arange(10)
print("An array from 0 to 9\n" + repr(arr) + "\n")
# Creating an array of floats
arr = np.arange(10.1)
print("An array of floats\n" + repr(arr) + "\n")
# The first and second arguments specify the start and end points
arr = np.arange(-5, 5)
print("An array from -5 to 5\n" + repr(arr) + "\n")
# Third argument specifies the step
arr = np.arange(-10, 10, 4)
print("An array from -10 to 10 with a step of 4\n" +
repr(arr))

Like np.array, np.arange performs upcasting. It also has the dtype keyword argument to manually cast the array.

RELATED TAGS

numpy
python
data sciences
arrays
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?