# NumPy Operations in python¶

## Arithmetic¶

You can easily perform array with array arithmetic, or scalar with array arithmetic. Let's see some examples:

In [1]:
import numpy as np
arr = np.arange(0,10)

In [2]:
arr + arr

Out[2]:
array([ 0,  2,  4,  6,  8, 10, 12, 14, 16, 18])
In [3]:
arr * arr

Out[3]:
array([ 0,  1,  4,  9, 16, 25, 36, 49, 64, 81])
In [4]:
arr - arr

Out[4]:
array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
In [6]:
# Warning on division by zero, but not an error!
# Just replaced with nan
arr/arr

C:\ProgramData\Anaconda3\lib\site-packages\ipykernel_launcher.py:3: RuntimeWarning: invalid value encountered in true_divide
This is separate from the ipykernel package so we can avoid doing imports until

Out[6]:
array([nan,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.])
In [7]:
# Also warning, but not an error instead infinity
1/arr

C:\ProgramData\Anaconda3\lib\site-packages\ipykernel_launcher.py:2: RuntimeWarning: divide by zero encountered in true_divide


Out[7]:
array([       inf, 1.        , 0.5       , 0.33333333, 0.25      ,
0.2       , 0.16666667, 0.14285714, 0.125     , 0.11111111])
In [10]:
arr**3

Out[10]:
array([  0,   1,   8,  27,  64, 125, 216, 343, 512, 729])

## Universal Array Functions¶

Numpy comes with many universal array functions, which are essentially just mathematical operations you can use to perform the operation across the array. Let's show some common ones:

In [12]:
#Taking Square Roots
np.sqrt(arr)

Out[12]:
array([ 0.        ,  1.        ,  1.41421356,  1.73205081,  2.        ,
2.23606798,  2.44948974,  2.64575131,  2.82842712,  3.        ])
In [13]:
#Calcualting exponential (e^)
np.exp(arr)

Out[13]:
array([  1.00000000e+00,   2.71828183e+00,   7.38905610e+00,
2.00855369e+01,   5.45981500e+01,   1.48413159e+02,
4.03428793e+02,   1.09663316e+03,   2.98095799e+03,
8.10308393e+03])
In [14]:
np.max(arr) #same as arr.max()

Out[14]:
9
In [15]:
np.sin(arr)

Out[15]:
array([ 0.        ,  0.84147098,  0.90929743,  0.14112001, -0.7568025 ,
-0.95892427, -0.2794155 ,  0.6569866 ,  0.98935825,  0.41211849])
In [16]:
np.log(arr)

/Users/marci/anaconda/lib/python3.5/site-packages/ipykernel/__main__.py:1: RuntimeWarning: divide by zero encountered in log
if __name__ == '__main__':

Out[16]:
array([       -inf,  0.        ,  0.69314718,  1.09861229,  1.38629436,
1.60943791,  1.79175947,  1.94591015,  2.07944154,  2.19722458])

## How Axis work in numpy¶

Suppose you want to calculate the sum of all the columns, the you can make use of axis.

In [10]:
a = np.array([(1,2,3),(3,4,5)])
a

Out[10]:
array([[1, 2, 3],
[3, 4, 5]])
In [9]:
# Add columns
print(a.sum(axis = 0))

[4 6 8]


so, as you see above sum of all columns has added where 1+3=4, 2+4=6,3+5=8.

In [11]:
# Add rows
print(a.sum(axis = 1))

[ 6 12]


so, similarly as you can see if you replace the axis by 1 then it prints [6,12], where all rows get added.

In [ ]:



That's all we need to know for now.. see you on next chapter..