Skip to content

Instantly share code, notes, and snippets.

@GeorgeSeif
Last active July 17, 2019 23:23
Show Gist options
  • Select an option

  • Save GeorgeSeif/2d2f457c6d765929bff34ee46f2f1b08 to your computer and use it in GitHub Desktop.

Select an option

Save GeorgeSeif/2d2f457c6d765929bff34ee46f2f1b08 to your computer and use it in GitHub Desktop.
# In Numpy, arithmetic operators on arrays are always applied elementwise.
# A new array is filled and returned with the result.
# For example, if we create 2 arrays a and b, and subtract b
# from a, we will get something like this. Remember that you
# can NOT do such an operation with arrays of differnt sizes,
# you'll get an error
a = np.array( [20,30,40,50] )
b = np.array( [0, 1, 2, 3] )
c = a - b
c = [20, 29, 38, 47]
# You can also perform scalar operations elementwise on the entire array
b**2
b = [0, 1, 4, 9]
# Or even apply functions
10*np.sin(a)
a = [ 9.12945251, -9.88031624, 7.4511316 , -2.62374854]
# Remember that operation between arrays are always applied elementwise
a = np.array( [20,30,40,50] )
b = np.array( [0, 1, 2, 3] )
c = a * b
c = [0, 30, 80, 150]
# There are many quick and useful functions in numpy that you will
# use frequently like these
a = np.array( [20,30,40,50] )
a.max() # 50
a.min() # 20
a.sum() # 140
# If you have a multi-dimensional array, use the "axis" parameter
b = np.arange(12).reshape(3,4)
b = [[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]]
b.sum(axis=0) # [12, 15, 18, 21]
b.min(axis=1) # [0, 4, 8]
b.cumsum(axis=1) # [[ 0, 1, 3, 6], [ 4, 9, 15, 22], [ 8, 17, 27, 38]]
# And if you need one, here are some more common ones that are a bit "mathy-er"
b = np.arange(3)
b = [0, 1, 2]
np.exp(b) # [ 1.0, 2.71828183, 7.3890561 ]
np.sqrt(b) # [ 0.0 , 1.0, 1.41421356]
np.floor(np.exp(b)) # [ 1.0, 2.0, 7.0 ]
np.round(np.exp(b)) # [ 1.0, 3.0, 7.0 ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment