About Lesson
NumPy Creating Arrays
NumPy provides several ways to create arrays, allowing for flexibility and convenience when working with data. Here are some common methods for creating arrays:
Creating Arrays from Lists
NumPy arrays can be created from Python lists using the numpy.array()
function.
Example: Creating a 1-D Array
import numpy as np
# Creating a 1-D array from a list
arr = np.array([1, 2, 3, 4, 5])
print(arr)
Output:
[1 2 3 4 5]
Example: Creating a 2-D Array
import numpy as np
# Creating a 2-D array from a list of lists
arr = np.array([[1, 2, 3], [4, 5, 6]])
print(arr)
Output:
[[1 2 3]
[4 5 6]]
Creating Arrays with Specific Functions
NumPy provides several functions to create arrays with specific values or patterns:
numpy.zeros()
– Create an array filled with zerosnumpy.ones()
– Create an array filled with onesnumpy.full()
– Create an array filled with a specified valuenumpy.arange()
– Create an array with a range of valuesnumpy.linspace()
– Create an array with evenly spaced values within a specified range
Example: Creating an Array of Zeros
import numpy as np
# Creating a 2x3 array filled with zeros
arr = np.zeros((2, 3))
print(arr)
Output:
[[0. 0. 0.]
[0. 0. 0.]]
Example: Creating an Array of Ones
import numpy as np
# Creating a 2x3 array filled with ones
arr = np.ones((2, 3))
print(arr)
Output:
[[1. 1. 1.]
[1. 1. 1.]]
Example: Creating an Array Filled with a Specific Value
import numpy as np
# Creating a 2x3 array filled with the value 7
arr = np.full((2, 3), 7)
print(arr)
Output:
[[7 7 7]
[7 7 7]]
Example: Creating an Array with a Range of Values
import numpy as np
# Creating an array with values from 0 to 9
arr = np.arange(10)
print(arr)
Output:
[0 1 2 3 4 5 6 7 8 9]
Example: Creating an Array with Evenly Spaced Values
import numpy as np
# Creating an array with 5 values evenly spaced between 0 and 1
arr = np.linspace(0, 1, 5)
print(arr)
Output:
[0. 0.25 0.5 0.75 1. ]
Creating Arrays from Existing Data
NumPy can create arrays from existing data, such as lists, tuples, or other arrays.
Example: Creating an Array from a Tuple
import numpy as np
# Creating an array from a tuple
arr = np.array((1, 2, 3, 4, 5))
print(arr)
Output:
[1 2 3 4 5]
Conclusion
In this chapter, we’ve covered various methods for creating NumPy arrays, including creating arrays from lists and tuples, as well as using specific NumPy functions to generate arrays with particular values or patterns.
Join the conversation