[Python Cookbook] Numpy: Multiple Ways to Create an Array

Posted Sherrrry

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[Python Cookbook] Numpy: Multiple Ways to Create an Array相关的知识,希望对你有一定的参考价值。

Convert from list

Apply np.array() method to convert a list to a numpy array:

1 import numpy as np
2 mylist = [1, 2, 3]
3 x = np.array(mylist)
4 x

Output: array([1, 2, 3])

Or just pass in a list directly:

y = np.array([4, 5, 6])
y

Output: array([4, 5, 6])

Pass in a list of lists to create a multidimensional array:

m = np.array([[7, 8, 9], [10, 11, 12]])
m

Output:

array([[ 7,  8,  9],

       [10, 11, 12]])

Array Generation Functions

arange returns evenly spaced values within a given interval.

n = np.arange(0, 30, 2) # start at 0 count up by 2, stop before 30
n

Output: 

array([ 0,  2,  4,  6,  8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28])

reshape returns an array with the same data with a new shape.

n = n.reshape(3, 5) # reshape array to be 3x5
n

Output:

array([[ 0,  2,  4,  6,  8],

       [10, 12, 14, 16, 18],

       [20, 22, 24, 26, 28]])

linspace returns evenly spaced numbers over a specified interval.

o = np.linspace(0, 4, 9) # return 9 evenly spaced values from 0 to 4
o

Output:

array([0. , 0.5, 1. , 1.5, 2. , 2.5, 3. , 3.5, 4. ])

resize changes the shape and size of array in-place.

o.resize(3, 3)
o

Output:

array([[0. , 0.5, 1. ],

       [1.5, 2. , 2.5],

       [3. , 3.5, 4. ]])

ones returns a new array of given shape and type, filled with ones.

np.ones((3, 2))

Output: 

array([[1., 1.],

       [1., 1.],

       [1., 1.]])

zeros returns a new array of given shape and type, filled with zeros.

np.zeros((2, 3))

Output:

array([[0., 0., 0.],

       [0., 0., 0.]])

eye returns a 2-D array with ones on the diagonal and zeros elsewhere.

np.eye(3)

Output:

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

       [0., 1., 0.],

       [0., 0., 1.]])

diag extracts a diagonal or constructs a diagonal array.

np.diag(y)

Output:

array([[4, 0, 0],

       [0, 5, 0],

       [0, 0, 6]])

Create an array using repeating list (or see np.tile)

np.array([1, 2, 3] * 3)

Output:

array([1, 2, 3, 1, 2, 3, 1, 2, 3])

Repeat elements of an array using repeat.

np.repeat([1, 2, 3], 3)

Output:

array([1, 1, 1, 2, 2, 2, 3, 3, 3])

Random Number Generator

The numpy.random subclass provides many methods for random sampling. The following tabels list funtions in the module to generate random numbers.

Simple random data

rand(d0, d1, ..., dn) Random values in a given shape.
randn(d0, d1, ..., dn) Return a sample (or samples) from the “standard normal” distribution.
randint(low[, high, size, dtype]) Return random integers from low (inclusive) to high (exclusive).
random_integers(low[, high, size]) Random integers of type np.int between low and high, inclusive.
random_sample([size]) Return random floats in the half-open interval [0.0, 1.0).
random([size]) Return random floats in the half-open interval [0.0, 1.0).
ranf([size]) Return random floats in the half-open interval [0.0, 1.0).
sample([size]) Return random floats in the half-open interval [0.0, 1.0).
choice(a[, size, replace, p]) Generates a random sample from a given 1-D array
bytes(length) Return random bytes.

 

Now I will summarize the usage of the first three funtions which I have met frequently.

numpy.random.rand creates an array of the given shape and populate it with random samples from a uniform  distribution over [0, 1). Parameters d0, d1, ..., dn define dimentions of returned array.

np.random.rand(2,3)

Output:

array([[0.20544659, 0.23520889, 0.11680902],

       [0.56246922, 0.60270525, 0.75224416]])

 

numpy.random.randn creates an array of the given shape and populate it with random samples from a strandard normal distribution N(0,1). If any of the 技术分享图片 are floats, they are first converted to integers by truncation. A single float randomly sampled from the distribution is returned if no argument is provided.

1 # single random variable
2 print(np.random.randn(),
)
3 # N(0,1)
4 print(np.random.randn(2, 4),
)
5 # N(3,6.26)
6 print(2.5 * np.random.randn(2, 4) + 3,
)

Output:

-1.613647405772221 

 

[[ 1.13147436  0.19641141 -0.62034454  0.61118876]

 [ 0.95742223  1.91138142  0.2736291   0.29787331]] 

 

[[ 1.997092    2.6460653   3.2408004  -0.81586404]

 [ 0.15120766  1.23676426  6.59249789 -1.04078213]] 

 

numpy. random.randint returns random integers from the “discrete uniform” distribution of the specified dtype in the interval [lowhigh). If high is None (the default), then results are from [0, low). The specific format is

numpy.random.randint(lowhigh=Nonesize=Nonedtype=‘l‘)

np.random.seed(10)
np.random.randint(100,200,(3,4))
np.random.randint(100,200)

Output:

array([[109, 115, 164, 128],

       [189, 193, 129, 108],

       [173, 100, 140, 136]])

 

109

 

There are another two funtions used for permutations. Both of them can randomly permute an array. The only difference is that shuffle changes the original array but permutation doesn‘t.

shuffle(x) Modify a sequence in-place by shuffling its contents.
permutation(x) Randomly permute a sequence, or return a permuted range.
np.random.permutation([1, 4, 9, 12, 15])

Output: array([ 9,  4,  1, 12, 15])

np.random.permutation(10)

Output: array([3, 7, 4, 6, 8, 2, 1, 5, 0, 9])

Usually, we use the following statements to perform random sampling:

permutation = list(np.random.permutation(m))  #m is the number of samples
shuffled_X = X[:, permutation]
shuffled_Y = Y[:, permutation].reshape((1,m))

 


以上是关于[Python Cookbook] Numpy: Multiple Ways to Create an Array的主要内容,如果未能解决你的问题,请参考以下文章

[Python Cookbook] Numpy: Multiple Ways to Create an Array

[Python Cookbook] Numpy Array Joint Methods: Append, Extend & Concatenate

Python Cookbook(第3版)中文版:15.11 用Cython写高性能的数组操作

从 C 代码调用 numpy 函数

python图像处理库 哪个好 知乎

OpenCV Cookbook by Eric