NumPy is a Python library that is used for scientific computing. It provides a powerful array object that can be used to store and manipulate large amounts of data efficiently. NumPy arrays are similar to lists in Python, but they are more efficient and provide many additional features.
Creating arrays in NumPy is a simple process. There are several ways to create arrays in NumPy, including:
The most common way to create an array in NumPy is to convert a list to an array. This can be done using the array()
function. The array()
function takes a list as an argument and returns an array.
<pre><code>import numpy as np
my_list = [1, 2, 3, 4, 5]
my_array = np.array(my_list)
print(my_array)</code></pre>
The output of this code will be:
[1 2 3 4 5]
You can also create an array with a specified shape and fill it with zeros using the zeros()
function. The zeros()
function takes a tuple as an argument that specifies the shape of the array.
<pre><code>import numpy as np
my_array = np.zeros((3, 4))
print(my_array)</code></pre>
The output of this code will be:
[[0. 0. 0. 0.]
[0. 0. 0. 0.]
[0. 0. 0. 0.]]
You can also create an array with a specified shape and fill it with ones using the ones()
function. The ones()
function takes a tuple as an argument that specifies the shape of the array.
<pre><code>import numpy as np
my_array = np.ones((2, 3))
print(my_array)</code></pre>
The output of this code will be:
[[1. 1. 1.]
[1. 1. 1.]]
You can also create an array with a range of values using the arange()
function. The arange()
function takes three arguments: start, stop, and step. The start argument specifies the starting value of the range, the stop argument specifies the ending value of the range (exclusive), and the step argument specifies the step size between values.
<pre><code>import numpy as np
my_array = np.arange(0, 10, 2)
print(my_array)</code></pre>
The output of this code will be:
[0 2 4 6 8]
You can also create an array with random values using the random()
function. The random()
function takes a tuple as an argument that specifies the shape of the array.
<pre><code>import numpy as np
my_array = np.random.random((2, 3))
print(my_array)</code></pre>
The output of this code will be:
[[0.12345678 0.98765432 0.87654321]
[0.23456789 0.34567891 0.45678901]]
These are just a few examples of the many ways to create arrays in NumPy. NumPy provides many additional functions for creating and manipulating arrays, making it a powerful tool for scientific computing.