Create An Array with NumPy
In [26]:
import numpy as np #import from python libary
a = np.array([1, 2, 3, 4, 5])
print a
print a*2
Out [26]:
Create A One-Dimensional Array¶
In [27]:
a = np.arange(20) # one dimension
print a
print a.shape
print a.ndim
print a.dtype
Create A Two-Dimensional Array¶
In [28]:
a = np.array([[1, 2, 3], [4, 5, 6]]) # two dimensions
print a
print a.shape
print a.ndim
print a.dtype
Create A Three-Dimensional Array¶
In [29]:
a = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]]) # three dimensions
print a
print a.shape
print a.ndim
print a.dtype
How to Generate an Array from a Sequence¶
In [21]:
print np.arange(20, 30, 2) # return evenly space numbers over a specified interval.(integers)
print np.linspace(0, 1, 20) # return evenly space numbers over a specified interval.(float numbers)
print np.random.rand(5)# returns random numbers between 0 and 1
Indexing and Slicing¶
Indexing and Slicing are very important when dealing with vast amounts of data. This allows you to cut down the array and narrow it to the part of the data you want to analyze.
In [39]:
In [39]:
print a
print a[0:2, 0:2, 2]
Manipulating Array Shape¶
Array shape manipulation can help when needing to perform operations with other multi-dimensional arrays.
In [54]:
In [54]:
b = np.copy(a)
b.shape = (12L,)
print b
Boolean Masking¶
Boolean Masking can help with cutting down an array given a specific condition. In this case the array "b" is a list of boolean values which are true when the value of a is a multiple of 5. "b" is then masked against "a" to get those values.
In [72]:
In [72]:
a = np.arange(0, 105) + 1
b = a%5==0
print a[b]
Element-wise Operations¶
Element wise operations are used to efficiently perform functional operations against each element of the array.
In [77]:
In [77]:
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
print a+b
Matrix Multiplication¶
In [78]:
a = np.array([[1, 2, 3], [4, 5, 6]])
b = np.array([[7, 8], [9, 10], [11, 12]])
a.dot(b)
Out[78]:
Logical Operations¶
In [86]:
c = a>2
d = a>8
print c
print d
print np.logical_and(c, d)
Basic Reductions¶
In [106]:
a.shape = (6L) # One dimension
print a
print np.sum(a)
print np.mean(a)
print np.std(a)
print np.size(a)
In [125]:
a = np.arange(0, 105) + 1
a.shape = (3L, 5L, 7L)
print a
print np.sum(np.sum(a, axis=2), axis=0)
In [126]:
sum(range(1, 8)+range(36, 43)+range(71, 78))
Out[126]:
No comments:
Post a Comment