1.2 NumPy Array Creation
来源:互联网 发布:java中数组怎么输入 编辑:程序博客网 时间:2024/05/16 06:14
Array Creation
There are several ways to create arrays.
For example, you can create an array from a regular Python list or tuple using the array function. The type of the resulting array is deduced(推断) from the type of the elements in the sequences.
>>> import numpy as np>>> a=np.array([2,3,4])>>> aarray([2, 3, 4])>>> a.dtypedtype('int32')>>> b=np.array([1.2,3.5,5.1])>>> b.dtypedtype('float64')
A frequent error consists in calling array with multiple numeric arguments, rather than providing a single list of numbers as an argument.
>>> a=np.array(1,2,3,4) # wrongTraceback (most recent call last): File "<stdin>", line 1, in <module>ValueError: only 2 non-keyword arguments accepted>>> a=np.array([1,2,3,4]) # right
array transforms(转换) sequences of sequences into two-dimensional arrays, sequences of sequences of sequences into three-dimensional arrays, and so on.
>>> b=np.array([(1.5,2,3),(4,5,6)])>>> barray([[ 1.5, 2. , 3. ], [ 4. , 5. , 6. ]])>>>>>> c=np.array([[1,2,3],[7,8,9]])>>> carray([[1, 2, 3], [7, 8, 9]])
The type of the array can also be explicitly specified at creation time:
>>> c=np.array([[1.5,2,3],[4,5,6]],dtype=complex)>>> carray([[ 1.5+0.j, 2.0+0.j, 3.0+0.j], [ 4.0+0.j, 5.0+0.j, 6.0+0.j]])>>> c.dtypedtype('complex128')
Often, the elements of an array are originally unknown, but its size is known. Hence(因此), NumPy offers several functions to create arrays with initial placeholder content. These minimize the necessity of growing arrays, an expensive(昂贵的) operation.
The function zeros creates an array full of zeros, the function ones creates an array full of ones, and the function empty creates an array whose initial content is random and depends on the state of the memory. By default, the dtype of the created array is float64.
>>> np.zeros((3,4))array([[ 0., 0., 0., 0.], [ 0., 0., 0., 0.], [ 0., 0., 0., 0.]])>>> np.ones((2,3,4),dtype=np.int16)array([[[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]], [[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]], dtype=int16)>>> np.empty((2,3))array([[ 1.5, 2. , 3. ], [ 4. , 5. , 6. ]])
To create sequences of numbers, NumPy provides a function analogous(相似的) to range that returns arrays instead of lists.
>>> np.arange(10,30,5)array([10, 15, 20, 25])>>> np.arange(0,2,0.3)array([ 0. , 0.3, 0.6, 0.9, 1.2, 1.5, 1.8])
When arange is used with floating point arguments, it is generally not possible to predict(预测) the number of elements obtained, due to the finite(有限的) floating point precision. For this reason, it is usually better to use the function linspace that receives as an argument the number of elements that we want, instead of the step:
>>> from numpy import pi>>> np.linspace(0,2,9) # 9 numbers from 0 to 2array([ 0. , 0.25, 0.5 , 0.75, 1. , 1.25, 1.5 , 1.75, 2. ])>>> x=np.linspace(0,2*pi,100) 100 numbers from 0 to 2*pi>>> f=np.sin(x)
提示:np.linspace函数返回一个等差数列。