NumPy Tutorial: A simple Example-Based Guide
Last updated: Aug23,2020

Summary: A clearly presented set of numpy recipes.


Here is the link:
NumPy Tutorial: A simple Exxample-Based Guide


SPECIAL Note: Have a look at
This useful set of articles.

The link above, where I found the numpy article, has a lot of useful articles. many involve Java and other stuff of little use to me, but there are lots of seemingly useful python things. Moreover, you can hit the little "Python" button at the top of the page, and this narroew things done to 39 pages. Each page has 8 articles. For instance, there is a simple article on page 4 named "Default Arguments in Python Finctions" that I really need to read! For instance, I used it, and an article on page 6 named "How to get the current Date and Time in Python", to start out my coding example in "np_big_examples.py".

I decided to go through this webdoc completely and just code up the examples in a single running piece of python code, I named it "np_big_examples.py".

 

Here is the source for np_big_examples.py:  
 
#!/usr/bin/env python

# Following exmaples frpm //stackabuse.com/numpy-tutorial-a-simple-example-based-guide/#numpyoperations

def anykey(): 
 rr = raw_input("\nEnter any key to continue = ")
 return rr

#===========================================================================
# Here is the start of my "main" program 
# This early stuff, including making the function above, are from reading 
# articles in the very useful:   https://stackabuse.com/
#===========================================================================

import numpy as np
from datetime import datetime

print "\nOutput from my test code:   /home/sco/NumPy/np_big_examples.py\n"
print "To run this code:     % python /home/sco/NumPy/np_big_examples.py \n"

#--------------------------------------------------------------------------
# I get the current time                    DEMO of TIME stuff 
current_datetime = datetime.now()
print type(current_datetime)
print "\ndate and time at start of this run: %s \n" % (current_datetime) 
year = current_datetime.year
print "The year is now                 = %s \n" % (year), 
print "The month number is now         = %s \n" % (current_datetime.month), 
print "The day number is now           = %s \n" % (current_datetime.day), 
print "The hour (time) is now          = %s \n" % (current_datetime.hour),
print "The minutes (time) is now       = %s \n" % (current_datetime.minute),
print "The seconds (time) is now       = %s \n" % (current_datetime.second),
print "The  microseconds (time) is now = %s \n" % (current_datetime.microsecond)

just_date = datetime.now().date()
print "Just a date string = %s \n" % (just_date),
just_time = datetime.now().time()
print "Just a time string = %s \n" % (just_time),

utnow = datetime.utcnow()
print "The UT time now    = %s \n" % (utnow),
#--------------------------------------------------------------------------

# Here I show how to use a simple user-defined function  
s1 = anykey() 
print "I use my defined function anykey():  type,value = %s, %s\n" % ( type(s1), s1 )   

#--------------------------------------------------------------------------
# Just for completeness, I use the text load method of 2darray_ex2.py
# To find out more I could:
# % ipython 
# In [1]: import numpy as np
#    ...: help(np.loadtxt)         
# This gives tons of info and I first see:   function loadtxt in module numpy 

# I read the text lines directly into a numpy array
b = np.loadtxt('test.txt', dtype=float)
print "\nHere is my loaded (from test.txt) numpy array (named b):\n",
print b
print "Type of b         = %s \n" % ( type(b) ),
print "b.dtype = ", b.dtype
print "b.shape = ", b.shape
print "b.ndim = ", b.ndim
print "b.size = ", b.size
ss = anykey()
#--------------------------------------------------------------------------

# Now I begin doing thisng directly from 
# https://stackabuse.com/numpy-tutorial-a-simple-example-based-guide/#numpyoperations

# I make a list, and turn it into a numpy ndarray (n-diemnsional array) 
x = [2, 3, 4, 5, 6]
nums = np.array( x ) 
print "type(x)    = %s " % ( type(x) ) 
print "type(nums) = %s " % ( type(nums) ) 
print nums 

print "\nI use the arange method to generate an array:  A1 = np.arange(2, 11, 2) \n", 
A1 = np.arange(2, 11, 2)
print "A1 = ", A1 

print "\nI use the linspace method to generate an array:  A2 = np.linspace(1, 10, 20) \n", 
A2 = np.linspace(1, 10, 20)
print "A2 = ", A2

print "\nI use the random module to generate an array:  A3 = np.random.rand(2,6) \n", 
A3 = np.random.rand(2,6)
print "A3 = ", A3
print "A3.shape = ", A3.shape

print "\nTo get the same as abovem but using a gaussian with mean=0 sigma=1:  A3g = np.random.randn(2,6) \n", 
A3g = np.random.randn(2,6)
print "A3g = ", A3g

print "\nTo get 5 random integers between 50 and 100:  A4 = np.random.randint(50,100,5) \n", 
A4 = np.random.randint(50,100,5)
print "A4 = ", A4


print "\nI reshape A2 to be 4x5:  A2new = A2.reshape(4,5) \n", 
A2new = A2.reshape(4,5)
print "A2new = ", A2new
print "*** I have made 4 rows , each with 5 columns, from the 20 elemenst f A2\n" 

print "\nWhat is reshape?   I do:   print type(np.reshape), ans here is what I get:\n",
print type(np.reshape)

print "\nWhat are stats of my A3g array?   \n",
print "A3g.mean() gives: %f \n" % ( A3g.mean() ),
print "A3g.std() gives: %f \n" % ( A3g.std() ),
print "A3g.min() gives: %f \n" % ( A3g.min() ),
print "A3g.max() gives: %f \n" % ( A3g.max() ),
print "A3g.argmax() gives me the index of the max value: ", A3g.argmax(),

ss = anykey() 

print "\nNow I generate a 9-element array for slicing experiments:  num = np.arange(1,10)    \n",
num = np.arange(1,10)
print "Here is num: ", num 
print "Here is num[0]  : ", num[0] 
print "Here is num[1:4]: ", num[1:4] 
print "Here is num[-1] : ", num[-1] 


print "\nNow I make a 2d array for slicing play:   nums2d = np.array( [ [1,2,3],[4,5,6],[7,8,9] ] ) \n",
nums2d = np.array( [ [1,2,3],[4,5,6],[7,8,9] ] )
print "Here is nums2d:\n", 
print(nums2d) 

print "\nIwant to print row 2:    print( nums2d[1,:] ) \n",
print( nums2d[1,:] )
print "\nIwant to print the first 2 elements of row 3, i.e.  7 8 :    print( nums2d[2,0:2] )\n",
print( nums2d[2,0:2] ) 
print "\nIwant to print the column 3, i.e.   :    print( nums2d[:,2] )\n",
print( nums2d[:,2] )
ss = anykey 

#-----------------------------------------------------------------
# Now I do some math 
print "\nI make a new arrya:     A5 = np.arange(1, 16)\n"
A5 = np.arange(1, 16)
print(A5), 
A6 = A5 + 10.0 
print "\nA6 = A5 + 10.0, I print A6: \n",
print A6 

print "\nI take the log of the members:    Blog = np.log(A6) \n",
Blog = np.log(A6)
print(Blog) 

print "\nI take the exp of the members of Blog:    Bexp = np.log(Blog) \n",
Bexp = np.exp(Blog)
print(Bexp),
print "    # Notice I get A6 back again! \n" 


print "\nI take the sqrt of the members of A6:    Bsqrt = np.sqrt(A6) \n",
Bsqrt = np.sqrt(A6)
print(Bsqrt)

print "\nI take the sin of the members of A6:    Bsin = np.sin(A6) \n",
Bsin = np.sin(A6)
print(Bsin)
print "NOTE: elements are in units of radians!\n" 


 

Here is a run:  
% python np_big_examples.py 

Output from my test code:   /home/sco/NumPy/np_big_examples.py

To run this code:     % python /home/sco/NumPy/np_big_examples.py 



date and time at start of this run: 2020-08-23 16:33:20.187495 

The year is now                 = 2020 
The month number is now         = 8 
The day number is now           = 23 
The hour (time) is now          = 16 
The minutes (time) is now       = 33 
The seconds (time) is now       = 20 
The  microseconds (time) is now = 187495 

Just a date string = 2020-08-23 
Just a time string = 16:33:20.187527 
The UT time now    = 2020-08-23 21:33:20.187531 

Enter any key to continue = Boot 
I use my defined function anykey():  type,value = , Boot


Here is my loaded (from test.txt) numpy array (named b):
[[1.1 1.2 1.3 1.4 1.5]
 [2.1 2.2 2.3 2.4 2.5]
 [3.1 3.2 3.3 3.4 3.5]]
Type of b         =  
b.dtype =  float64
b.shape =  (3, 5)
b.ndim =  2
b.size =  15

Enter any key to continue = My answer 
type(x)    =  
type(nums) =  
[2 3 4 5 6]

I use the arange method to generate an array:  A1 = np.arange(2, 11, 2) 
A1 =  [ 2  4  6  8 10]

I use the linspace method to generate an array:  A2 = np.linspace(1, 10, 20) 
A2 =  [ 1.          1.47368421  1.94736842  2.42105263  2.89473684  3.36842105
  3.84210526  4.31578947  4.78947368  5.26315789  5.73684211  6.21052632
  6.68421053  7.15789474  7.63157895  8.10526316  8.57894737  9.05263158
  9.52631579 10.        ]

I use the random module to generate an array:  A3 = np.random.rand(2,6) 
A3 =  [[0.3978989  0.12105978 0.75914616 0.937583   0.51945677 0.90087656]
 [0.59219778 0.81088236 0.01729787 0.74102429 0.53944398 0.17641226]]
A3.shape =  (2, 6)

To get the same as abovem but using a gaussian with mean=0 sigma=1:  A3g = np.random.randn(2,6) 
A3g =  [[ 1.63442436  1.1188107   0.7282905  -0.52592227 -0.52455239  0.49032327]
 [ 0.51917032 -1.04750827  0.57425342 -1.26995444 -1.25693003  1.38053183]]

To get 5 random integers between 50 and 100:  A4 = np.random.randint(50,100,5) 
A4 =  [63 57 98 85 78]

I reshape A2 to be 4x5:  A2new = A2.reshape(4,5) 
A2new =  [[ 1.          1.47368421  1.94736842  2.42105263  2.89473684]
 [ 3.36842105  3.84210526  4.31578947  4.78947368  5.26315789]
 [ 5.73684211  6.21052632  6.68421053  7.15789474  7.63157895]
 [ 8.10526316  8.57894737  9.05263158  9.52631579 10.        ]]
*** I have made 4 rows , each with 5 columns, from the 20 elemenst f A2


What is reshape?   I do:   print type(np.reshape), ans here is what I get:


What are stats of my A3g array?   
A3g.mean() gives: 0.151745 
A3g.std() gives: 0.990136 
A3g.min() gives: -1.269954 
A3g.max() gives: 1.634424 
A3g.argmax() gives me the index of the max value:  0 
Enter any key to continue = hh 

Now I generate a 9-element array for slicing experiments:  num = np.arange(1,10)    
Here is num:  [1 2 3 4 5 6 7 8 9]
Here is num[0]  :  1
Here is num[1:4]:  [2 3 4]
Here is num[-1] :  9

Now I make a 2d array for slicing play:   nums2d = np.array( [ [1,2,3],[4,5,6],[7,8,9] ] ) 
Here is nums2d:
[[1 2 3]
 [4 5 6]
 [7 8 9]]

Iwant to print row 2:    print( nums2d[1,:] ) 
[4 5 6]

Iwant to print the first 2 elements of row 3, i.e.  7 8 :    print( nums2d[2,0:2] )
[7 8]

Iwant to print the column 3, i.e.   :    print( nums2d[:,2] )
[3 6 9]

I make a new arrya:     A5 = np.arange(1, 16)

[ 1  2  3  4  5  6  7  8  9 10 11 12 13 14 15] 
A6 = A5 + 10.0, I print A6: 
[11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. 22. 23. 24. 25.]

I take the log of the members:    Blog = np.log(A6) 
[2.39789527 2.48490665 2.56494936 2.63905733 2.7080502  2.77258872
 2.83321334 2.89037176 2.94443898 2.99573227 3.04452244 3.09104245
 3.13549422 3.17805383 3.21887582]

I take the exp of the members of Blog:    Bexp = np.log(Blog) 
[11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. 22. 23. 24. 25.]     # Notice I get A6 back again! 


I take the sqrt of the members of A6:    Bsqrt = np.sqrt(A6) 
[3.31662479 3.46410162 3.60555128 3.74165739 3.87298335 4.
 4.12310563 4.24264069 4.35889894 4.47213595 4.58257569 4.69041576
 4.79583152 4.89897949 5.        ]

I take the sin of the members of A6:    Bsin = np.sin(A6) 
[-0.99999021 -0.53657292  0.42016704  0.99060736  0.65028784 -0.28790332
 -0.96139749 -0.75098725  0.14987721  0.91294525  0.83665564 -0.00885131
 -0.8462204  -0.90557836 -0.13235175]
NOTE: elements are in units of radians!


I left out a few matrix operations, but this is a lot of stuff.




Back to SCO code page