Self Numpy
Self Numpy
1. Installation of NumPy
2. Importing NumPy
After installing NumPy, it must be imported into your Python script. It’s a
common practice to import NumPy as np to save time when referencing the
library:
import numpy as np
3. Using numpy as np
Example:
print(array)
4. NumPy as ndarray
Example:
5. Dimensions in Arrays
dtype: The desired data type of the array, e.g., int, float.
copy: If True, the data is copied. If False, changes in the original object will
reflect in the array.
order: Memory layout for the array. 'C' is row-major (C-style), 'F' is column-
major (Fortran-style).
subok: If True, subclasses of ndarray are passed. If False, the base class is
forced.
ndmin: Specifies the minimum number of dimensions for the output array.
Example:
print(array)
In this example, the ndmin parameter forces the array to have at least two
dimensions.
You can create a NumPy array from a Python list. This is the most basic way
to create a NumPy array:
my_list = [1, 2, 3, 4]
array = np.array(my_list)
print(array)
# Output: [1 2 3 4]
Example:
array = np.array(42)
print(array.ndim) # Output: 0
print(array.ndim) # Output: 1
print(array.ndim) # Output: 2
print(array.ndim) # Output: 3
The ndim attribute tells you the number of dimensions of the array.
You can check the number of dimensions in an array using .ndim. This
attribute returns an integer representing the number of axes or dimensions.
print(array.ndim) # Output: 1
NumPy supports arrays of more than 3 dimensions. For instance, you can
create a 5D array using the ndmin parameter.
Example:
print(array.ndim) # Output: 5
Shape: The shape of an array is a tuple that tells how many elements are in
each dimension.
The array has 3 rows and 2 columns, so the shape is (3, 2).
For example, summing along axis 0 adds up all the elements in each column:
Example:
reshaped = array.reshape(2, 3)
print(reshaped)
# Output:
# [[1 2 3]
# [4 5 6]]
Reshape Notes:
The new shape must be compatible with the number of elements in the
original array.
print(reshaped)
# Output:
# [[1 2]
# [3 4]
# [5 6]]