美文网首页
Creating Arrays

Creating Arrays

作者: 我是聪 | 来源:发表于2018-12-28 14:41 被阅读0次

There are functions provided by Numpy to create arrays with evenly spaced values within a given interval. One 'arange' uses a given distance and the other one 'linspace' needs the number of elements and creates the distance

arange

arange([start, ] stop[, step], [,dtype = None])

arange returns evenly spaced values within a given interval. The values are generated within the half-open interval

'[start, stop)' If the function is used with integers,it is nearly equivalent to the Python built-in function range,but arange returns an ndarray rather than a list iterator as range does.If the 'start ' parameter is not given,it will be set to 0. The end of the interval is dertermined by the parameter 'stop '. The spacing between two adjacent values of the output array is set with the optional parameter 'step'. The default value for 'step ' is 1.If the parameter 'step' is given , the 'start' parameter cannot be optional,i.e. it has to be given as well. The type of the output array can be specified with the automatically inferred from the other input arguments.

import numpy as np 

a  = np.arange(1, 10)

x = range(1, 10)

x = np.arange(0.5 ,10.4, 0.8)

x = np.arange(0.5, 10.4, 0.8, int)

linspace

linspace(start, stop, num = 50, endpoint = True, retstep = False)

Shape of an Array

The function "shape " returns the shape of an array. The shape is a tuple of integers. These numbers denote the lengths of the corresponding array dimension.In other words: The "shape " of an array is a tuple with the number of the elements per axis(dimension).

x = np.array( [[67, 63, 87],

                      [77, 69, 59],

                      [85, 87, 99],

                      [79, 72, 71],

                      [63, 89, 93],

                      [68, 92, 78]])

print(np.shape(x))

print(x.shape)

The shape of an array tells us also sth about the order in which the indices are processes

"shape " can also be used to change the shape of an array

x.shape = (3, 6)     x.shape(2, 9)

Indexing and Slicing

Assigning to and accessing the elements of an array is similiar to other sequential data types of Python,i.e. lists and tuples.

F = np.array([1, 1, 2, 3, 5, 8, 13, 21 ])

print(F[0])    print(F[-1])

Indexing multidimensional arrays:

A = np.array([ [3.4, 8.7, 9.9],

                        [1.1, -7.8, -0.7],

                        [4.1, 12.3, 4.8])

print(A[1][0])

You have to be aware of the fact,that way of accessing multi-dimensional arrays can be highly inefficient.The reason is that we create an intermediate array A[1] from which we access the element with index 0.

tmp = A[1]    print(tmp[0])

There is another way to access elements of multi-dimensional arrays in Numpy: 

We use only one pair of square brackets and all the indices are separated by commas:

print(A[1,0])

S = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

print(S[2:5])    print(S[:4])    print([6:])    print(S[:])

A = np.array([

                    [11, 12, 13, 14, 15],

                    [21, 22, 23, 24, 25],

                    [31, 32, 33, 34, 35],

                    [41, 42, 43, 44, 45],

                    [51, 52, 53, 54, 55]])

print(A[:3, 2:])

The following two examples use the third parameter "step".

X = np.arange(28).reshape(4, 7)

print(X[::2, ::3])    print(X[::, ::3])

If the number of objects in the selection tuple is less than the dimension N.

Then : is assumed for any subsequent dimensions:

A = np.array(

        [    [45, 12, 4], [45, 13, 5], [46, 12, 6]    ],

        [    [46, 14, 4], [45, 14, 5], [46, 11, 5]    ],

        [    [47, 13, 2], [48, 15, 5], [52, 15, 1]    ]    ])

A[1:3, 0:2]    # equivalent to A[1:3, 0:2, :]

Attention: Whereas slicings on lists and tuples creates new objects, a slicing operation on an array creates a view on the original array.So we get an another possibility to access the array, or better a part of the array.From this follows that if we modify a view, the original array will be modified as well.

A = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

S = A[2:6]

S[0] = 22 

S[1] = 23    print(A)    [0, 1, 22, 23, 4, 5, 6, 7, 8, 9]

Doing the similiar thing with lists, we can see that we get a copy:

lst = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

lst2 = lst[2:6]

lst2[0] = 22    lst2[1] = 23    print(lst)    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Creating Arrays with Ones, Zeros and Empty

There are two ways of initializing Arrays with Zeros or Ones. The method ones(t) takes a tuple(元组) t with the shape of the array and fills the array accordingly with ones.By default it will be filled with Ones of type float.If you need integer Ones , you have to set the optionnal parameter dtype to int:

import numpy as np

E = np.ones((2, 3))

F = np.ones((3, 4),dtype = int )

There is another interesting way to create an array with Ones or with Zeros, if it has to have the same shape as another existing array 'a'. Numpy supplies for this purpose the methods ones_like(a) and zeros_like(a).

x = np.array([2, 5, 18, 14, 4])

E = np.ones_like(x)

Z = np.zeros_like(x)

Copying Arrays

numpy.copy()

copy(obj, order = 'K')

Return an array copy of the given object 'obj'

Parameter Meaning

obj    array_like input data.

order    The possible values are {'C', 'F', 'A', 'K'}. This parameter controls the memory layout of the copy.

'C' means C-order, 'F' means Fortran-order, 'A' means 'F' if the object 'obj' is Fortran contiguous, 'C' otherwise.

'K' means match the layout of 'obj' as closely as possible.

import numpy as np 

x = np.array([[42, 22, 12],[44,53,66][44, 53, 66]], order = 'F')

y = x.copy()

ndarray.copy()

There is also a ndarray method 'copy',which can be directly applied to an array

a.copy(order = 'C')

Returns a copy of the array 'a'

Parameter Meaning 

order    The same as with numpy.copy,but 'C' is the default value for order.

import numpy as np

x = np.array([42, 22, 12], [44, 53, 66], order = 'F')

y = x.copy()

Identity Array

In linear algebra, the identity matrix, or unit matrix, of size n is the n * n square matrix with ones on the main 

diagonal and zeros elsewhere. identiy and eye.

The identity Function 

identity(n,dtype = None)

Parameter Meaning

n    An integer number defining the number of rows and columns of the output,i.e. 'n' x 'n'

dtype    An optional argument,defining the data-type of the output.The default is 'float'

The output of identity is an 'n' * 'n' array with its main diagonal set to one and all other elements are 0.

import numpy as np

np.identify(4)

np.identify(4, dtype = int ) # equivalent to np.identity(3, int)

array( [ 1, 0, 0, 0 ],

           [ 0, 1, 0, 0 ],

           [ 0, 0, 1, 0 ],

           [ 0, 0, 0, 1 ] )

The eye Function

Another way to create identity arrays provides the function eye. 

This function creates also diagnonal arrays consisting solely of ones.

import numpy as np 

np.eye( 5, 8, k = 1, dtype = int )

相关文章

网友评论

      本文标题:Creating Arrays

      本文链接:https://www.haomeiwen.com/subject/ahnvkqtx.html