-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path2_Arrays.py
More file actions
96 lines (87 loc) · 2.41 KB
/
Copy path2_Arrays.py
File metadata and controls
96 lines (87 loc) · 2.41 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
# NumPy is used to work with arrays. The array object in NumPy is called ndarray. We can create a NumPy ndarray object by using the array() function.
# 1 Introction to numpy
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
print(arr)
print(type(arr))
"""
output:
[1 2 3 4 5]
<class 'numpy.ndarray'>
"""
_________________________________________________
# Use a tuple to create a NumPy array:
import numpy as np
arr = np.array((1, 2, 3, 4, 5))
print(arr) #[1 2 3 4 5]
__________________________________________________
# Dimensions in Arrays :
"""
A dimension in arrays is one level of array depth (nested arrays).
nested array: are arrays that have arrays as their elements.
> 0-D Arrays :
0-D arrays, or Scalars, are the elements in an array. Each value in an array is a 0-D array.
"""
import numpy as np
arr = np.array(42)
print(arr) # 42
# 1-D Arrays :An array that has 0-D arrays as its elements is called uni-dimensional or 1-D array.
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
print(arr) #[1 2 3 4 5]
#2-D Arrays
"""
An array that has 1-D arrays as its elements is called a 2-D array.
These are often used to represent matrix or 2nd order tensors.
NumPy has a whole sub module dedicated towards matrix operations called numpy.mat
"""
import numpy as np
arr = np.array([[1, 2, 3], [4, 5, 6]])
print(arr)
# output [[1 2 3][4 5 6]]
# 3-D arrays
"""
An array that has 2-D arrays (matrices) as its elements is called 3-D array.
These are often used to represent a 3rd order tensor.
"""
import numpy as np
arr = np.array([[[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [4, 5, 6]]])
print(arr)
"""
[[[1 2 3]
[4 5 6]]
[[1 2 3]
[4 5 6]]]
"""
# Check Number of Dimensions : NumPy Arrays provides the ndim attribute that returns an integer that tells us how many dimensions the array have.
import numpy as np
a = np.array(42)
b = np.array([1, 2, 3, 4, 5])
c = np.array([[1, 2, 3], [4, 5, 6]])
d = np.array([[[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [4, 5, 6]]])
print(a.ndim)
print(b.ndim)
print(c.ndim)
print(d.ndim)
"""
Output:
0
1
2
3
"""
# Higher Dimensional Arrays
"""
An array can have any number of dimensions.
When the array is created, you can define the number of dimensions by using the ndmin argument.
Example
Create an array with 5 dimensions and verify that it has 5 dimensions:
"""
import numpy as np
arr = np.array([1, 2, 3, 4], ndmin=5)
print(arr)
print('number of dimensions :', arr.ndim)
"""
[[[[[1 2 3 4]]]]]
number of dimensions : 5
"""