-
Pandas Basics 5
-
Lecture1.1
-
Lecture1.2
-
Lecture1.3
-
Lecture1.4
-
Lecture1.5
-
-
Data Transformations 6
-
Lecture2.1
-
Lecture2.2
-
Lecture2.3
-
Lecture2.4
-
Lecture2.5
-
Lecture2.6
-
-
Statistics 4
-
Lecture3.1
-
Lecture3.2
-
Lecture3.3
-
Lecture3.4
-
-
Reading and Writing Data 3
-
Lecture4.1
-
Lecture4.2
-
Lecture4.3
-
-
Joins 5
-
Lecture5.1
-
Lecture5.2
-
Lecture5.3
-
Lecture5.4
-
Lecture5.5
-
-
Grouping 4
-
Lecture6.1
-
Lecture6.2
-
Lecture6.3
-
Lecture6.4
-
-
Introduction to Numpy 4
-
Lecture7.1
-
Lecture7.2
-
Lecture7.3
-
Lecture7.4
-
-
Randomness 2
-
Lecture8.1
-
Lecture8.2
-
-
Numpy Data Functionality 1
-
Lecture9.1
-
Extending to 2 Dimensions
Extending to 2 Dimensions¶
One of the biggest differences you will see with numpy is its support for higher dimension arrays. If we give it a nested list, we will get back a 2 dimensional array. So first create the following array.
#Create a two dimensional array
ar1 = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
[10, 11, 12]])
print(ar1)
[[ 1 2 3]
[ 4 5 6]
[ 7 8 9]
[10 11 12]]
The shape attribute will return the dimensions of the array. In the case of the 2d array, it will give the number of rows x number of columns.
#Print the shape
print(ar1.shape)
(4, 3)
If you use the indexing from before, you will get the first row, and the first two rows. You can try it out to see.
#Basic indexing
print(ar1[0])
print()
print(ar1[:2])
[1 2 3]
[[1 2 3]
[4 5 6]]
One thing that you can't do with basic lists is to index along the columns instead. If you give ":" for the rows (meaning return all rows), then you can use the indexing for the columns to get back the first column as well as the first two columns. Notice how the shapes look for each! The first one will give back a one dimensional array.
#Basic indexing for columns
print(ar1[:,0])
print()
print(ar1[:,:2])
[ 1 4 7 10]
[[ 1 2]
[ 4 5]
[ 7 8]
[10 11]]
As well, different operations can be used for numpy arrays together. Things like adding two numpy arrays together will add them element by element. So for example, the following code creates a second array, then adds the first and second array.
#Create array 2
ar2 = ar1.copy() * 2
#Add array 1 and array 2
print("Array 1:")
print(ar1)
print()
print("Array 2:")
print(ar2)
print()
ar3 = ar1 + ar2
print("Array 3 (Array 1 + Array 2):")
print(ar3)
Array 1:
[[ 1 2 3]
[ 4 5 6]
[ 7 8 9]
[10 11 12]]
Array 2:
[[ 2 4 6]
[ 8 10 12]
[14 16 18]
[20 22 24]]
Array 3 (Array 1 + Array 2):
[[ 3 6 9]
[12 15 18]
[21 24 27]
[30 33 36]]