import numpy as np
a = np.arange(10)
b = a[:2]
print "from ",a
print "we slice", b
from [0 1 2 3 4 5 6 7 8 9]
we slice [0 1]
a = np.arange(10)
b = a[2:7]
print "now from ",a
print "we slice", b
now from [0 1 2 3 4 5 6 7 8 9]
we slice [2 3 4 5 6]
a = np.arange(10)
b = a[7]
print "from ",a
print "we slice", b
from [0 1 2 3 4 5 6 7 8 9]
we slice 7
If only one parameter is put, a single item corresponding to the index will be returned. If a : is inserted in front of it, all items from that index onwards will be extracted. If two parameters (with : between them) is used, items between the two indexes (not including the stop index) with default step one are sliced.
a = np.arange(10)
b = a[7:-1]
print "from ",a
print "we slice", b
from [0 1 2 3 4 5 6 7 8 9]
we slice [7 8]
or more advanced…
x = np.arange(12).reshape(4,3)
print 'Our array is:'
print x
print '\n'
rows = np.array([[0,0],[-1,-1]])
cols = np.array([[0,-1],[0,-1]])
print "rows are", rows
print "columns are", cols
y = x[rows,cols]
print 'The corner elements of this array are:'
print y
Our array is:
[[ 0 1 2]
[ 3 4 5]
[ 6 7 8]
[ 9 10 11]]
rows are [[ 0 0]
[-1 -1]]
columns are [[ 0 -1]
[ 0 -1]]
The corner elements of this array are:
[[ 0 2]
[ 9 11]]
a = np.arange(9, dtype = np.float_).reshape(3,3)
print 'First array:'
print a
print '\n'
print 'Second array:'
b = np.array([10,10,10])
print b
print '\n'
print 'Add the two arrays:'
print np.add(a,b)
print '\n'
print 'Subtract the two arrays:'
print np.subtract(a,b)
print '\n'
print 'Multiply the two arrays:'
print np.multiply(a,b)
print '\n'
print 'Divide the two arrays:'
print np.divide(a,b)
print 'Applying power function:'
print np.power(a,2)
a = np.array([0,30,45,60,90])
print 'Sine of different angles:'
# Convert to radians by multiplying with pi/180
print np.sin(a*np.pi/180)
print '\n'
print 'Cosine values for angles in array:'
print np.cos(a*np.pi/180)
print '\n'
print 'Tangent values for given angles:'
print np.tan(a*np.pi/180)
Sine of different angles:
[ 0. 0.5 0.70710678 0.8660254 1. ]
Cosine values for angles in array:
[ 1.00000000e+00 8.66025404e-01 7.07106781e-01 5.00000000e-01
6.12323400e-17]
Tangent values for given angles:
[ 0.00000000e+00 5.77350269e-01 1.00000000e+00 1.73205081e+00
1.63312394e+16]
a = np.array([1.0,5.55, 123, 0.567, 25.532])
print 'Original array:'
print a
print '\n'
print 'After rounding:'
print np.around(a)
print np.around(a, decimals = 1)
print np.around(a, decimals = -1)