We can set seed for random number generation. Which will make sure that the random numbers are generated always the same.
import numpy as np
def test_run():
np.random.seed(100)
array = np.random.randint(0, 10, size=(3,4))
print array
if __name__ == "__main__":
test_run()
So, everytime we run this code, we get the same result.
[[8 8 3 7]
[7 0 4 2]
[5 2 2 2]]
Sum all elements in array
import numpy as np
def test_run():
print array
print array.sum()
if __name__ == "__main__":
test_run()
Here is sum.
[[1 2 3]
[2 3 4]]
15
Sum of each column and row
import numpy as np
def test_run():
array = np.array([(1, 2, 3), (2, 3, 4)])
print array
print array.sum(0) # sum of columns
print array.sum(1) # sum of rows
if __name__ == "__main__":
test_run()
Here are the sums.
[3 5 7]
[6 9]
Finding max, min and mean in an array
import numpy as np
def test_run():
array = np.array([(1, 2, 3), (2, 3, 4)])
print array
print array.max(0) # max of first column
print array.min(0) # min of first column
print array.mean() # mean of all elements
if __name__ == "__main__":
test_run()
Her are the values.
[[1 2 3]
[2 3 4]]
[2 3 4]
[1 2 3]
2.5
There are more functions available, check this page.
Find index of max value
import numpy as np
def get_max_index(a):
return np.argmax(a)
def test_run():
a = np.array([9, 6, 2, 3, 12, 14, 7, 10], dtype=np.int32) # 32-bit integer array
print "Array:", a
# Find the maximum and its index in array
print "Maximum value:", a.max()
print "Index of max.:", get_max_index(a)
if __name__ == "__main__":
test_run()
Here is the output.
Array: [ 9 6 2 3 12 14 7 10]
Maximum value: 14
Index of max.: 5
Glue arrays together
There are many ways to append or connect two arrays. Depends what we really need.
Append one array to another array.
In [1]: import numpy as np
In [2]: a = np.array([[1, 2, 3], [4, 5, 6]])
In [3]: b = np.array([[9, 8, 7], [6, 5, 4]])
In [4]: np.concatenate((a, b))
Out[4]:
array([[1, 2, 3],
[4, 5, 6],
[9, 8, 7],
[6, 5, 4]])
Or we can do the same thing using vstack function.
In [1]: a = np.array([1, 2, 3])
In [2]: b = np.array([4, 5, 6])
In [3]: np.vstack((a, b))
Out[3]:
array([[1, 2, 3],
[4, 5, 6]])
Or using hstack to do it horizontally.
a = np.array((1,2,3))
b = np.array((2,3,4))
np.hstack((a,b))
a = np.array([[1],[2],[3]])
b = np.array([[2],[3],[4]])
np.hstack((a,b))
First argument ":" makes sure all rows are included. Second argument if more complex. 0 and 3 are saying what values to take. 2 is saying what will be skipped. Here is the output.