Let’s start with the basics. Import the library, create a list and then convert it to an array with NumPy.
Let’s create another list, combine the two and then put both of them to an array. The array at this point becomes two dimensional.
If you want to know the shape of an array, try the follow
This returns a tuple and it shows my array is 2 by 4. In other words, my array has 2 rows and 4 columns. You can use the same way to create 3, 4, 5, …. n number of rows and columns. You can also easily initialize your array with zeros. There are two ways:
Finding the data type of an array is easy as follows:
To create a 5×5 array of 1s, use the following method:
To create an Identity Matrix, use the eye method like the following:
arange is a very cool method you can use to initialize your array. Check the documentation for details but here are some examples:
You can also initialize by providing what value to start at, when to end and how many spaces/steps between values. Here is what I mean:
Let’s do some scalar operations on array.
Let’s reshape an array.
Transposing an array is easy. Here is how:
Let’s learn about some Universal Array Functions (in short ufuncs). These are functions you can apply to every value in an array. Details at Python ufunc
You can also compare the values at each index from the two arrays and return the max.
We’ll plot some graph and it will require some additional graph plotting library called Matplotlib. I have been using iPython Notebook to show all the code and output here. The next concept will also require some iPython Notebook specific coding to display graphs and I will use comments when needed.
Try following the code segments below. Try to experiment with each to have better understanding. We will replace all of it with a shorter version.
You can replace the above code segments with numpy’s where method like the following:
Let’s create an 5×5 array with random values.
We’ll use Numpy’s where method to replace any value in the array that is less zero with zero. We’ll leave everything else the same.
Let’s learn about some very useful array methods.
Let’s create some sample income data, centered around $54,000 with a normal distribution (remember bell-shaped graph?), a standard deviation of 10,000, and with 10,000 data points. We’ll also look at mean and median values.
You can save the contents of an array to a file and read it back like the following:
You can save multiple arrays in a zip file.