“This is the second day of my participation in the Gwen Challenge.
The main feature of the NumPy library is the introduction of arrays. Arrays are similar to lists, so let’s use lists to get a feel for the basic concepts of arrays. The demo code is shown below.
Import numpy as np a = [1,2,3,4] b = np. Array ([1,2,3,4]) print(a) print(b) print(type(a)) print(type(b))Copy the code
The code to introduce the NumPy library in line 1 is “import NumPy as NP”, so that later code can replace NumPy with NP, which is simpler. The np.array() function in line 3 creates an array from a list. The output is as follows
[1,2,3,4] [1,2,3,4Copy the code
Next access the elements in the list and array by indexing and slicing as follows.
print(a[1])
print(b[1])
print(a[0:2])
print(b[0:2])
Copy the code
The output is as follows:
[1,2] [1,2]Copy the code
As you can see from the output, lists and arrays share the same indexing mechanism, with the only difference being that elements in arrays are separated by Spaces and elements in lists are separated by commas.
From the above analysis, we know that arrays and lists are very similar, so why do we use arrays and not lists in our data analysis? There are many reasons for this. Here are two main reasons. First, NumPy, as a library dedicated to data processing, does a good job of supporting math that is more cumbersome to do with lists. The demo code is shown below.
c = a*2
d = b*2
print(c)
print(d)
Copy the code
The running results are as follows:
[1,2,3,4,1,2,3,4] [2,4, 6, 8]Copy the code
You can see that when you do the same multiplication, the list copies the elements, whereas the array multiplies each element. Second, lists store one-dimensional data, whereas arrays store multidimensional data. What do I mean by one-dimensional data and multidimensional data? We can use concepts from solid geometry to help us understand: one dimension is like a straight line, and many dimensions are like a plane (two dimensions) or a solid (three dimensions), etc. The data in a table is one-dimensional, whereas the table data in an Excel worksheet is two-dimensional. The demo code is shown below.
E = [[1, 2], [3, 4], [5, 6]] f = np, array ([[1, 2], [3, 4], [5, 6]])Copy the code
The printout for list e and array f is:
[[1,2],[3,4],[5,6]]
[[1 2]
[3 4]
[5 6]]
Copy the code
As you can see, the structure of list E is one-dimensional, although it contains three small lists. The array f is a two-dimensional structure with three rows and two columns. It is the core of the library for learning pandas.