20 methods for creating ndarrary in Python

Source: Internet
Author: User
Tags iterable

Complete example of this article: complete sample code
This article describes the basic, common ways to create ndarrary, with sample code.

First, create through Ndarray
importas np
1.1 One-dimensional arrays
= np.array([123])a
array([1, 2, 3])
1.2 Two-dimensional arrays
np.array([[1234],       [2345]])
array([[1, 2, 3, 4],       [2, 3, 4, 5]])
1.3 Three-dimensional array
= np.array([    [        [123223],        [233233]    ],    [        [1234],        [233432]    ]])print(arr1)print(type(arr1))arr1
[[[ 1  2 32 23]  [23  3 23  3]] [[ 1  2  3  4]  [23  3  4 32]]]<class ‘numpy.ndarray‘>array([[[ 1,  2, 32, 23],        [23,  3, 23,  3]],       [[ 1,  2,  3,  4],        [23,  3,  4, 32]]])
Second, the common function of creating Ndarrary 2. The zeros () function, which specifies a dimension tuple (shape parameter), returns a total of 0 ndarrary
= np.zeros((24))arr2
array([[ 0.,  0.,  0.,  0.],       [ 0.,  0.,  0.,  0.]])
3. Ones () function, specify a dimension tuple (shape parameter), return all 1 ndarrary
= np.ones((44))arr3
array([[ 1.,  1.,  1.,  1.],       [ 1.,  1.,  1.,  1.],       [ 1.,  1.,  1.,  1.],       [ 1.,  1.,  1.,  1.]])
4. Empty () function, specifying a dimension tuple (shape parameter), returns a value (garbage value) as the initialized Ndarrary
= np.empty((22))arr4
array([[  7.89119642e-312,   4.22795269e-307],       [  9.34608432e-307,   1.11258854e-306]])
Iii. other ways to create ndarrary 5. Numpy.arange ([start], stop[, step], dtype=none) function, left open right closed
= np.arange(1101)arr5
array([1, 2, 3, 4, 5, 6, 7, 8, 9])
6. Numpy.linspace (Start, Stop, num=50, Endpoint=true, Retstep=false, dtype=none) function, generate a arithmetic progression, left closed right
= np.linspace(045)arr6
array([ 0.,  1.,  2.,  3.,  4.])
7. Numpy.logspace (Start, Stop, num=50, Endpoint=true, base=10.0, Dtype=none) functions, base default is 10
= np.logspace(045, base=2)arr7
array([  1.,   2.,   4.,   8.,  16.])
8. Numpy.eye (N, M=none, k=0, dtype=

Return a 2-d array with ones on the diagonal and zeros elsewhere.

= np.eye(43)arr8
array([[ 1.,  0.,  0.],       [ 0.,  1.,  0.],       [ 0.,  0.,  1.],       [ 0.,  0.,  0.]])
9. Numpy.zeros_like (A, Dtype=none, order= ' K ', subok=true) function, returns an array of all 0 elements with the same shape parameter as a

Return an array of zeros with the same shape and type as a given array.
Parameter subok, whether to inherit the data type of A;
The parameter order, which specifies the stored layout of the returned results in memory, is ' K ' by default, indicating as much as possible as a.

# 返回一个与arr8形状应的全0数组= np.zeros_like(arr8)arr9
array([[ 0.,  0.,  0.],       [ 0.,  0.,  0.],       [ 0.,  0.,  0.],       [ 0.,  0.,  0.]])
Numpy.ones_like (A, Dtype=none, order= ' K ', subok=true) function,

Returns an array that is the same as the shape parameter of a and the element is all 0

# 返回一个与ar9形状应的全0数组= np.ones_like(arr9)arr10
array([[ 1.,  1.,  1.],       [ 1.,  1.,  1.],       [ 1.,  1.,  1.],       [ 1.,  1.,  1.]])
Numpy.empty_like (A, Dtype=none, order= ' K ', subok=true) functions, returns an array with the same shape and all values as garbage values (random values)

Return a new array with the same shape and type as a given array.

= np.empty_like(np.ones((5,4)))arr11
array([[  7.89102294e-312,   6.27463370e-322,   0.00000000e+000,          0.00000000e+000],       [  8.45593933e-307,   5.30276956e+180,   7.70748458e-043,          4.57487963e-071],       [  3.45618033e-086,   3.35860426e-143,   6.01433264e+175,          6.93885958e+218],       [  5.56218858e+180,   3.94356143e+180,   4.75084178e-037,          1.24689504e-047],       [  3.85156077e-057,   2.06073242e+184,   4.71530148e-143,          1.50008929e+248]])
Numpy.copy (A, order= ' K ') function, returns the same array as a

Return An array copy of the given object.

# 属于深拷贝,修改复制数组,对原数组没有影响= np.copy(arr11)arr12[00=1arr12
array([[  1.00000000e+000,   6.27463370e-322,   0.00000000e+000,          0.00000000e+000],       [  8.45593933e-307,   5.30276956e+180,   7.70748458e-043,          4.57487963e-071],       [  3.45618033e-086,   3.35860426e-143,   6.01433264e+175,          6.93885958e+218],       [  5.56218858e+180,   3.94356143e+180,   4.75084178e-037,          1.24689504e-047],       [  3.85156077e-057,   2.06073242e+184,   4.71530148e-143,          1.50008929e+248]])
Numpy.identity (n, dtype=none) function, returns an n-order unit square

Return the identity array.

= np.identity(4)arr13
array([[ 1.,  0.,  0.,  0.],       [ 0.,  1.,  0.,  0.],       [ 0.,  0.,  1.,  0.],       [ 0.,  0.,  0.,  1.]])
Numpy.fromfunction (function, shape, **kwargs) returns an array in which the value of the element is computed by the function, and the shape is limited by the form tuple
Note: The parameter shape is a tuple, and the number of elements in the shape tuple needs to match the number of parameters in the function, representing different latitudes.
= np.fromfunction(lambda x, y: x+y, shape=(33))print= np.fromfunction(lambda x, y, z: x+y+z, shape=(333))arr21
[[ 0.  1.  2.] [ 1.  2.  3.] [ 2.  3.  4.]]array([[[ 0.,  1.,  2.],        [ 1.,  2.,  3.],        [ 2.,  3.,  4.]],       [[ 1.,  2.,  3.],        [ 2.,  3.,  4.],        [ 3.,  4.,  5.]],       [[ 2.,  3.,  4.],        [ 3.,  4.,  5.],        [ 4.,  5.,  6.]]])
Numpy.mgrid functions
arr14 =  np.mgrid[ - 1 : 3 : 2 ] # means starting from 1, step 1, Take 2 numbers  print  (arr14) arr15 =  np.mgrid[-  1 : 3 : 2j] # when added ' J ', means left closed right closed, and takes 2 numbers  span class= "bu" >print  (arr15) arr16 =  np.mgrid[- 1 : 3 ] # when specifying two parameters, the function is the same as the Numpy.arange () function  span class= "bu" >print  (arr16) arr18 =  np.mgrid[0 : 5 , 0 : 5 ] # do padding on two dimensions respectively  print  (arr18)  
[-1  1][-1.  3.][-1  0  1  2][[[0 0 0 0 0]  [1 1 1 1 1]  [2 2 2 2 2]  [3 3 3 3 3]  [4 4 4 4 4]] [[0 1 2 3 4]  [0 1 2 3 4]  [0 1 2 3 4]  [0 1 2 3 4]  [0 1 2 3 4]]]
Numpy.ogrid functions
= np.ogrid[1:2]print= np.ogrid[0:50:5]print(arr20)
[1][array([[0],       [1],       [2],       [3],       [4]]), array([[0, 1, 2, 3, 4]])]
Numpy.fromstring (String, Dtype=float, Count=-1, sep= ") function to create a one-dimensional ndarrary from a string
= np.fromstring(‘1 2 3 4‘, sep=‘ ‘)arr21
array([ 1.,  2.,  3.,  4.])
Numpy.fromiter (iterable, Dtype, count=-1) function, returns a one-dimensional array
# 需要指定数据类型dtype= (i*forinrange(4= np.fromiter(iterable,dtype=float)arr22
array([ 0.,  1.,  4.,  9.])
Iv. other methods 19. The Numpy.fromfile (file, Dtype=float, Count=-1, sep= ") function creates ndarrary20 from a text file or binary file. numpy.loadtxt(fname, dtype=<type ‘float’>, comments=’#’, delimiter=None, converters=None,skiprows=0, usecols=None, unpack=False, ndmin=0)Created from the file.
Summarize
    1. Complete example of this article: complete sample code
    2. Limited capacity, welcome to the wrong communication;

Welcome to the personal public number Waltsmithml or Sina Weibo waltsmith, which offers free video tutorials on machine learning, deep learning, Hadoop, Spark, Python, Math, and more. My main direction is machine learning and deep learning. Very welcome to exchange study ha, in addition to study, but also free to help download paper or books ha ==============
??? Public number????????? Sina micro-blog??

20 methods for creating ndarrary in Python

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.