0%

numpy_100

python中的[1:], [::-1], [:,m:n]
1
2
3
4
5
6
7
8
9
10
11
12
b = a[i:j]	# 表示复制a[i]到a[j - 1],以生成新的list对象
'''
当i缺省时,默认为0,即a[:3]相当于a[0:3]
当j缺省时,默认是len,即a[1:]相当于a[1:len]
当i,j都缺省时,a[:]就相当于完整复制一份a了
'''
b = a[i:j:s] # 这种格式,i与j一样,但s表示步进,缺省为1
'''
所以,a[i:j:1]相当于a[i:j]
当s < 0: i缺省时,默认为-1,j缺省时,默认为-len(a)-1
所以a[::-1]相当于,a[-1: -len(a)-1: -1],也就是从最后一个元素到第一个元素复制一遍
'''

X[:, 0]是numpy中数组的一种用法,表示对一个二维数组,取该二维数组第一维中的所有数据,第二维中取0个数据,直观来说,X[:, 0]就是取所以劥的第0个数据,X[:, 1]就是取所有行的第1个数据。

X[n, :]是取第1维中下标为n的元素的所有值

X[:, m:n],即取所有数据的第m到n-1列数据,含左不含右

1579089547890

Create a vector with values ranging from 10 to 49

1579093222023

Reverse a vector (first element becomes last)

1579093248133

Create a 8x8 matrix and fill it with a checkerboard pattern
1
2
3
4
Z = np.zeros((8,8),dtype=int)
Z[1::2,::2] = 1
Z[::2,1::2] = 1
print(Z)
获取一个多维数组中100号元素的位置
1
print(np.unravel_index(99, (6, 7, 8)))
Create a 5x5 matrix with values 1,2,3,4 just below the diagonal

1579093050294

Create a 2d array with 1 on the border and 0 inside

1579093085615

Create a random vector of size 30 and find the mean value

1579093304847

Create a 10x10 array with random values and find the minimum and maximum values

1579093328061

Create a 3x3 matrix with values ranging from 0 to 8

1579093359329

How to add a border (filled with 0’s) around an existing array?

1579093117787

Find indices of non-zero elements from [1,2,0,0,4,0]

获取值不为0的元素的下标

1579093158435

Create a checkerboard 8x8 matrix using the tile function

1579270024757

Normalize a 5x5 random matrix

1579270061711

Multiply a 5x3 matrix by a 3x2 matrix (real matrix product)

1579270093322

Given a 1D array, negate all elements which are between 3 and 8, in place

1579270119245

What is the output of the following script?

1579270162925

python自带的sum函数如下:

sum(iterable, [start])

后一个参数指定的是初始化值,会加到结果中去,故结果是-1+1+2+3+4=9

numpy中sum函数为:

numpy.sum(a, axis=None, dtype=None, out=None, keepdims=, initial=)

不使用命名参数,即将-1传给了axis,结果为10。如果要指定初始值,这样用np.sum(range(1, 5), initial=-1)

1579270615187

What are the result of the following expressions?

1579270626365

How to find common values between two arrays?

1579270897405

How to get all the dates corresponding to the month of July 2016?

1579614878714

Extract the integer part of a random array using 5 different methods

1579614931269

Consider a generator function that generates 10 integers and use it to build an array
1579614961104
How to sum a small array faster than np.sum?
1579615041630
Consider two random array A and B, check if they are equal?

1579615106684

Create a structured array with x and y coordinates covering the [0,1]x[0,1] area?

1579615148383

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# 关于np.subtract.outer
'''
a = np.array([5, 6, 7])
b = np.array([9, 12, 10])
np.subtract.outer(b, a)
输出为:
array([[4, 3, 2],
[7, 6, 5],
[5, 4, 3]])
看似没有规律,实际上是
9 - 5 = 4
9 - 6 = 3
9 - 7 = 2

12 - 5 = 7
12 - 6 = 6
12 - 7 = 5

10 - 5 = 5
10 - 6 = 4
10 - 7 = 3

其实上面的三行代码等价于
b[:, None] - a
关于b[:, None]
输出为:
array([[ 9],
[12],
[10]])

实际上是利用numpy数组的广播特性实现的
'''
How to find the closest value (to a given scalar) in a vector?

1579615269476

Create a structured array representing a position (x,y) and a color (r,g,b)?

1579615294710

参考:https://www.jianshu.com/p/d09778f4e055

关于python中的yield
  • 通常的for…in…循环中,in后面是一个数组,这个数组就是一个可迭代对象,类似的还有链表,字符串,文件。它可以是mylist = [1, 2, 3],也可以是mylist = [x*x for x in range(3)]。
    它的缺陷是所有数据都在内存中,如果有海量数据的话将会非常耗内存。

  • 生成器是可以迭代的,但只可以读取它一次。因为用的时候才生成。比如 mygenerator = (x*x for x in range(3)),注意这里用到了(),它就不是数组,而上面的例子是[]。

  • 我理解的生成器(generator)能够迭代的关键是它有一个next()方法,工作原理就是通过重复调用next()方法,直到捕获一个异常。可以用上面的mygenerator测试。

  • 带有 yield 的函数不再是一个普通函数,而是一个生成器generator,可用于迭代,工作原理同上。

  • eld 是一个类似 return 的关键字,迭代一次遇到yield时就返回yield后面(右边)的值。重点是:下一次迭代时,从上一次迭代遇到的yield后面的代码(下一行)开始执行。

  • 带有yield的函数不仅仅只用于for循环中,而且可用于某个函数的参数,只要这个函数的参数允许迭代参数。比如array.extend函数,它的原型是array.extend(iterable)。

  • send(msg)与next()的区别在于send可以传递参数给yield表达式,这时传递的参数会作为yield表达式的值,而yield的参数是返回给调用者的值。——换句话说,就是send可以强行修改上一个yield表达式值。比如函数中有一个yield赋值,a = yield 5,第一次迭代到这里会返回5,a还没有赋值。第二次迭代时,使用.send(10),那么,就是强行修改yield 5表达式的值为10,本来是5的,那么a=10

  • send(msg)与next()都有返回值,它们的返回值是当前迭代遇到yield时,yield后面表达式的值,其实就是当前迭代中yield后面的参数。

  • 第一次调用时必须先next()或send(None),否则会报错,send后之所以为None是因为这时候没有上一个yield(根据第8条)。可以认为,next()等同于send(None)。

示例:

1579616013658

理解的关键在于:下次迭代时,代码从yield的下一条语句开始执行

1579616104088

1579616134292

1579616447926

numpy.random.uiform(low=0.0, high=1.0, size=None)

生成size个符合均匀分布的浮点数,取值范围为[low, high),默认取值范围是[0.0, 1.0)

1
2
import scipy
import scipy.spitial

上面这个库有下面这个函数(皮),可以非常方便的用于计算两个输入集合之间的距离

scipy.spatial.distance.cdist(XA, XB, metric='euclidean', p=None, V=None, VI=None, w=None)

该函数用于计算两个输入集合的距离,通过metric参数指定计算距离的不同方式得到冉的距离度量值。

metric的取值有狠毒哦,例如chebyshev(契比雪夫距离), euclidean(欧氏距离), hamming(汉明距离), cosine(余弦夹角), colleration(相关系数), jaccard(杰卡德相似系数), mahalamobis(马氏距离), minkowski(闵可夫斯基距离)

How to convert a float (32 bits) array into an integer (32 bits) in place?

1580269432746

How to read the following file?

1580269653886

genfromtxt()函数创建数组表格数据,主要执行两个循环。第一个循环将文件的每一行转换成字符串序列,第二个循环将每个字符串序列转换成相应数据类型。

genfromtxt能够考虑缺失的数据,但其他更快和更简单的函数像loadtxt不能考虑缺失值。

What is the equivalent of enumerate for numpy arrays?

1580269827406

1580269840356

np.meshgrid() :生成网格点坐标矩阵

这里写图片描述

上图中,每个交叉点就是网格点,描述这些网格点的坐标的矩阵,就是坐标矩阵

坐标矩阵——横坐标矩阵X中的每个元素与纵坐标矩阵Y中对应位置元素,共同构成一个点的完整坐标

np.put()np.take()

numpytake函数与put函数有着与神奇索引类似的作用,take函数可以用于获取数组子集,而put函数可以设置数组子集。

take函数:

1
2
3
arr = np.arange(6) * 100 # 初始化数组为[0, 100, 200, 300, 400, 500]
inds = [4, 3, 2]
arr.take(inds) # 相当于从arr序列中一次获取索引为4, 3, 2位置上的索引,因此输出为array([400, 300, 200])

put函数:

1
2
3
arr = np.arange(6) * 100
inds = [4, 3, 2]
arr.put(inds, 11) # 相当于将arr序列中索引为4, 3, 2位置上的元素用11来替换

np.random.choice(a, size=None, replace=True, p=None)

从a(只要是ndarray都可以,但必须是一维的)中随机抽取数字,并组成指定大小(size)的数组

replace:True表示可以取相同数字,False表示不可以取相同的数字

数组p:与数组a相对应,表示取数组a中每个元素的概率,默认为选取每个元素的概率相同

对于axis的理解

https://blog.csdn.net/weixin_37821353/article/details/88367211

简要的来说:

首先将矩阵下标理解称为如下形式:

1580302428839

然后axis = n就表示仅仅第n个下标变化,其余下标不变的为一组,然后再进行操作。

如上图,如果axis = 0,则仅仅把第一个坐标变化,其他两个坐标一致的分为一组,因为分组之后的数组大小为:[4, 5]

How to sort an array by the nth column?

1580302844321

numpy.ndarray.flat() 将数组转换为1-D的迭代器,flat返回的是一个迭代器,可以用for访问数组的每一个元素

python 多维切片之冒号和三个点

https://blog.csdn.net/z13653662052/article/details/78010654

python中的None代表新增加一个维度,别称为newaxisNone放在哪一维,就会在哪一维上出现新的维度。

三个点表示省略所有的冒号来用省略号代替,即a[:, :, None]a[..., None]是一样的,因为...代替了前面两个冒号

np.bincount(x, weight=None, minlength=None)

bin的数量比x中的最大值大1,每个bin给出了它的索引值在x中出现的次数。

举例:

1
2
3
4
5
6
7
8
9
10
11
# 我们可以看到x中最大的数为7,因此bin的数量为8,那么它的索引值为0->7
x = np.array([0, 1, 1, 3, 2, 1, 7])
# 索引0出现了1次,索引1出现了3次......索引5出现了0次......
np.bincount(x)
#因此,输出结果为:array([1, 3, 1, 1, 0, 0, 0, 1])

# 我们可以看到x中最大的数为7,因此bin的数量为8,那么它的索引值为0->7
x = np.array([7, 6, 2, 1, 4])
# 索引0出现了0次,索引1出现了1次......索引5出现了0次......
np.bincount(x)
#输出结果为:array([0, 1, 1, 0, 1, 0, 1, 1])

weights这个参数。文档说,如果weights参数被指定,那么x会被它加权,也就是说,如果值n发现在位置i,那么out[n] += weight[i]而不是out[n] += 1.**因此,我们weights的大小必须与x相同,否则报错。

1
2
3
4
5
6
7
8
9
10
w = np.array([0.3, 0.5, 0.2, 0.7, 1., -0.6])
# 我们可以看到x中最大的数为4,因此bin的数量为5,那么它的索引值为0->4
x = np.array([2, 1, 3, 4, 4, 3])
# 索引0 -> 0
# 索引1 -> w[1] = 0.5
# 索引2 -> w[0] = 0.3
# 索引3 -> w[2] + w[5] = 0.2 - 0.6 = -0.4
# 索引4 -> w[3] + w[4] = 0.7 + 1 = 1.7
np.bincount(x, weights=w)
# 因此,输出结果为:array([ 0. , 0.5, 0.3, -0.4, 1.7])

文档说,如果minlength被指定,那么输出数组中bin的数量至少为它指定的数(如果必要的话,bin的数量会更大,这取决于x)。

1
2
3
4
5
6
7
8
9
10
11
# 我们可以看到x中最大的数为3,因此bin的数量为4,那么它的索引值为0->3
x = np.array([3, 2, 1, 3, 1])
# 本来bin的数量为4,现在我们指定了参数为7,因此现在bin的数量为7,所以现在它的索引值为0->6
np.bincount(x, minlength=7)
# 因此,输出结果为:array([0, 2, 1, 2, 0, 0, 0])

# 我们可以看到x中最大的数为3,因此bin的数量为4,那么它的索引值为0->3
x = np.array([3, 2, 1, 3, 1])
# 本来bin的数量为4,现在我们指定了参数为1,那么它指定的数量小于原本的数量,因此这个参数失去了作用,索引值还是0->3
np.bincount(x, minlength=1)
# 因此,输出结果为:array([0, 2, 1, 2])

np.add.at()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#np.add.at(dW, x, dout)
#dW[x] += dout # this will not work, see the doc of np.add.at
a = np.array([1,2,3,4,5,6,7])
i = np.array([0,1,2,0,1])
b = np.array([1,2,3,4,5])
np.add.at(a, i, b)
print(a)
a = np.array([1,2,3,4,5,6,7])
i = np.array([0,1,2,0,1])
b = np.array([1,2,3,4,5])
a[i] += b
print(a)
'''
output:
[6 9 6 4 5 6 7]
[5 7 6 4 5 6 7]
输出如下,即索引重复的时候,只有np.add.at会累积前面的结果,单纯的索引会取最后一次的结果覆盖
'''
Considering a four dimensions array, how to get sum over the last two axis at once?

1580305751799

1580305782512

1580305819784

np.roll(a, shift, axis=None):沿着给定轴滚动数组元素。超出最后位置的元素将会滚动到第一个位置(将a沿着axis的方向,滚动shift长度)

np.repeat(a, repeats, axis=None)这边的repeats可以是一个数,也可以是一个矩阵。

1580308200576

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
'''
np.cumsum(a, axis=None, dtype=None, out=None)
axis=0,按照行累加。
axis=1,按照列累加。
axis不给定具体值,就把numpy数组当成一个一维数组。
'''
a = np.array([[1,2,3], [4,5,6]])
'''
array([[1, 2, 3],
[4, 5, 6]])
'''
np.cumsum(a)
'''
array([ 1, 3, 6, 10, 15, 21])
'''
np.cumsum(a,axis=0) #按照行累加,行求和
'''
array([[1, 2, 3],
[5, 7, 9]])
[1, 2, 3]------> |1 |2 |3 |
[4, 5, 6]------> |5=1+4 |7=2+5 |9=3+6|
'''
np.cumsum(a,axis=1) #按照列累加,列求和
'''
array([[ 1, 3, 6],
[ 4, 9, 15]])
[1, 2, 3]------> |1 |2+1 |3+2+1 |
[4, 5, 6]------> |4 |4+5 |4+5+6 |
'''

np.stride_tricks.as_strided(x, shap, strides, subok, writeable)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import numpy as np

# 数独是个 9x9 的二维数组
# 包含 9 个 3x3 的九宫格
sudoku = np.array([
[2, 8, 7, 1, 6, 5, 9, 4, 3],
[9, 5, 4, 7, 3, 2, 1, 6, 8],
[6, 1, 3, 8, 4, 9, 7, 5, 2],
[8, 7, 9, 6, 5, 1, 2, 3, 4],
[4, 2, 1, 3, 9, 8, 6, 7, 5],
[3, 6, 5, 4, 2, 7, 8, 9, 1],
[1, 9, 8, 5, 7, 3, 4, 2, 6],
[5, 4, 2, 9, 1, 6, 3, 8, 7],
[7, 3, 6, 2, 8, 4, 5, 1, 9]
])

# 要将其变成 3x3x3x3 的四维数组
# 但不能直接 reshape,因为这样会把一行变成一个九宫格
shape = (3, 3, 3, 3)

# 大行之间隔 27 个元素,大列之间隔 3 个元素
# 小行之间隔 9 个元素,小列之间隔 1 个元素
strides = sudoku.itemsize * np.array([27, 3, 9, 1])

squares = np.lib.stride_tricks.as_strided(sudoku, shape=shape, strides=strides)
print(squares)

'''
[[[[2 8 7] [9 5 4] [6 1 3]]
[[1 6 5] [7 3 2] [8 4 9]]
[[9 4 3] [1 6 8] [7 5 2]]]

[[[8 7 9] [4 2 1] [3 6 5]]
[[6 5 1] [3 9 8] [4 2 7]]
[[2 3 4] [6 7 5] [8 9 1]]]

[[[1 9 8] [5 4 2] [7 3 6]]
[[5 7 3] [9 1 6] [2 8 4]]
[[4 2 6] [3 8 7] [5 1 9]]]]
实际上就是按照shape对数组进行切块
'''
Compute a matrix rank

1580370305230