Quick Ways to Create Arrays [Sept. 4, 2012, 1:02 a.m.]
There are other ways you can create arrays, other than explicitly typing the elements of the array using the array() function. Here are some of them.
Arrays with All Elements Zeros
Let us create a one-dimensioned array with 5 elements, all of which are zeros
x = numpy.zeros(5)
print type(x)
<type 'numpy.ndarray'>
print type(x[0])
<type 'numpy.float64'>
print x
[0. 0. 0. 0. 0.]
print x.shape
(5L,)
The same result could be achieved if we had used the following command to create the array:
x = numpy.zeros((5,))
The following points are worth noting:
- Elements of array x are float64, not int32
- The function zeros() takes as its input, the shape of the array to be created. When you wish to create a one dimensioned array, its shape can be input either as a single integer number or as a tuple (5,). When a tuple consists of only one element, the comma after the element is required
We can similarly create two- or three- or multi-dimensioned arrays with all elements zeros.
a = numpy.zeros((2, 4))
print a
[[ 0. 0. 0. 0.]
[ 0. 0. 0. 0.]]
b = numpy.zeros((2, 3, 4))
print b
[[[ 0. 0. 0. 0.]
[ 0. 0. 0. 0.]
[ 0. 0. 0. 0.]]
[[ 0. 0. 0. 0.]
[ 0. 0. 0. 0.]
[ 0. 0. 0. 0.]]]
Arrays with All Elements Ones
The function ones() is similar to the function zeros().
x = numpy.ones(5)
print x
[ 1. 1. 1. 1. 1.]
y = numpy.ones((2, 3))
print y
[[ 1. 1. 1.]
[ 1. 1. 1.]]
z = numpy.ones((2, 3, 4))
print z
[[[ 1. 1. 1. 1.]
[ 1. 1. 1. 1.]
[ 1. 1. 1. 1.]]
[[ 1. 1. 1. 1.]
[ 1. 1. 1. 1.]
[ 1. 1. 1. 1.]]]
Arrays with Random Numbers as its Elements
The NumPy function numpy.random.rand() creates arrays of specified shape whose elements are random numbers from a uniform distribution.
x = numpy.random.rand(2,3)
print x
[[ 0.39162673 0.88469785 0.45560386]
[ 0.12829358 0.24247348 0.70161319]]
ote the following points:
- The input arguments indicate that