[Python Cookbook] Numpy: Multiple Ways to Create an Array
Convert from list
Apply np.array() method to convert a list to a numpy array:
import numpy as np
mylist = [1, 2, 3]
x = np.array(mylist)
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

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.
# single random variable
print(np.random.randn(),'\n')
# N(0,1)
print(np.random.randn(2, 4),'\n')
# N(3,6.26)
print(2.5 * np.random.randn(2, 4) + 3,'\n')
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 [low, high). If high is None (the default), then results are from [0, low). The specific format is
numpy.random.randint(low, high=None, size=None, dtype='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
Permutation
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.

Here are some examples of permutation.
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」Numpy equivalent of MATLAB's cell array
转自Stackoverflow.备忘用. Question I want to create a MATLAB-like cell array in Numpy. How can I accompli ...
- [Python Cookbook] Numpy Array Slicing and Indexing
1-D Array Indexing Use bracket notation [ ] to get the value at a specific index. Remember that inde ...
- [Python Cookbook] Numpy: Iterating Over Arrays
1. Using for-loop Iterate along row axis: import numpy as np x=np.array([[1,2,3],[4,5,6]]) for i in ...
- [Python Cookbook] Numpy Array Joint Methods: Append, Extend & Concatenate
数组拼接方法一 思路:首先将数组转成列表,然后利用列表的拼接函数append().extend()等进行拼接处理,最后将列表转成数组. 示例1: import numpy as np a=np.arr ...
- [Python Cookbook] Numpy: How to Apply a Function to 1D Slices along the Given Axis
Here is a function in Numpy module which could apply a function to 1D slices along the Given Axis. I ...
- [Python Cookbook] Pandas: 3 Ways to define a DataFrame
Using Series (Row-Wise) import pandas as pd purchase_1 = pd.Series({'Name': 'Chris', 'Item Purchased ...
- [Python Cookbook] Numpy Array Manipulation
1. Reshape: The np.reshape() method will give a new shape to an array without changing its data. Not ...
- [转]python与numpy基础
来源于:https://github.com/HanXiaoyang/python-and-numpy-tutorial/blob/master/python-numpy-tutorial.ipynb ...
- 【Python】numpy 数组拼接、分割
摘自https://docs.scipy.org 1.The Basics 1.1 numpy 数组基础 NumPy’s array class is called ndarray. ndarray. ...
随机推荐
- 其它- in-place
in-place 刷编程题的时候,经常遇到题目要求do in-place.所以就上网搜了相关概念,简单总结一下. in-place操作,意思是所有的操作都是”就地“操作,不允许进行移动,或者称作 ...
- 用私有构造器或者枚举类型强化Singleton属性
1.Singleton指仅仅被实例化一次的类.Singleton通常被用来代表那些本质上唯一的系统组件,如窗口管理器或者文件系统.使类称为Singleton会使它的客户端调试变的十分困难,因为无法给S ...
- laravel5.2总结--ORM模型
ORM模型简介 1>什么是ORM? ORM,即 Object-Relational Mapping(对象关系映射),它的作用是在关系型数据库和业务实体对象之间作一个映射,这样,我们在操作具体的 ...
- 我给女朋友讲编程总结建议篇,怎么学习html和css
总共写了11篇博客了,7篇讲html的,4篇讲网络的.不敢说写的多么好吧,最起码的是我迈出了写作的第一步,写作的过程中了解了一些其他的知识,比如SEO.几种重定向等,由于个人能力和见识有限,写出来的东 ...
- IOS开发学习笔记038-autolayout 自动布局 界面实现
在storyboard/xib文件中实现自动布局 autolayout 1.注意事项 autolayout和frame属性是有冲突的,所以如果准备使用autolayout,就不要再代码中对控件的fra ...
- MFC定时关机程序的实现2-添加启动项到注册表
虽然上一篇实现了的定时关机,但是还不够完善,比如开机自动启动,然后按照配置的时间定时关机,并最小化到任务栏. 先来说开机启动怎么实现,开机启动实现的方法有好几种,比如直接在开始菜单启动项里添加一个程序 ...
- 简单实现nodejs爬虫工具
约30行代码实现一个简单nodejs爬虫工具,定时抓取网页数据. 使用npm模块 request---简单http请求客户端.(轻量级) fs---nodejs文件模块. index.js var ...
- Selenium 中 高亮元素
//高亮元素 WebElement element = driver.findElement(By.cssSelector(".table1 .btn-public label" ...
- Java和C#中神奇的String
Java String: String 类适用于描述字符串事物.该类是不可以被继承的.我们主要学习: 1字符串特性.字符串最大的特性:一旦被初始化就不可以被改变.重赋值只是改变了引用. 2字符串操作. ...
- Sql数据表中的关系