干货在最后总结哦
我是深圳大学大三的一名大学生,未来想要从事数据分析的工作
从今天开始学习python相关库
第一步是学习numpy!!!
每天一节,加油!
这篇文章是我的第一篇博文,错题整理为个人复习用
资料来源:https://github.com/fengdu78/Data-Science-Notes
Let x be array [[1, 2, 3], [4, 5, 6]]. Convert it to [1 4 2 5 3 6].
x = np.arange(1,7).reshape(2,3)
print(x)
# x.flatten(order='K')
x.flatten('F')
'''
order : {'C', 'F', 'A', 'K'}, optional
'C' means to flatten in row-major (C-style) order.
'F' means to flatten in column-major (Fortran-
style) order. 'A' means to flatten in column-major
order if `a` is Fortran *contiguous* in memory,
row-major order otherwise. 'K' means to flatten
`a` in the order the elements occur in memory.
The default is 'C'.
'''
flatten方法的参数order中,’C’代表行为主,‘F’代表列为主
Let x be an arbitrary 3-D array of shape (3, 4, 5). Permute the dimensions of x such that the new shape will be (4,3,5).
x = np.arange(3*4*5).reshape([3,4,5])
print(x)
out1 =np.reshape(x,[4,3,5])
out2 = np.swapaxes(x,1,0)
np.allclose(out1,out2)
print('out1:',out1)
print('out2:',out2)
可以看到reshape和swapaxes两个函数得到的是不一样的
reshape保留原来的顺序
swapaxes则是交换两个坐标轴
Let x be an arbitrary 3-D array of shape (3, 4, 1). Remove a single-dimensional entries such that the new shape will be (3, 4).
# help(np.squeeze) 利用squeeze函数
x=np.zeros([3,4,1])
# 不指定axis的话就会去除所有长度为1的轴 如果指定不是1的轴就会报错
# np.squeeze(x)
#
np.squeeze(x,axis=2)
Lex x be an array
[[ 1 2 3]
[ 4 5 6].
and y be an array
[[ 7 8 9]
[10 11 12]].
Concatenate x and y so that a new array looks like
[[1, 2, 3, 7, 8, 9],
[4, 5, 6, 10, 11, 12]].
x = np.arange(1,7).reshape(2,3)
y = np.arange(7,13).reshape(2,3)
np.hstack((x,y))
#如果竖直合成 则使用hstack
Let x be an array [1 2 3] and y be [4 5 6]. Convert it to [[1, 4], [2, 5], [3, 6]].
# help(np.dstack)
x = np.array([1,2,3])
y = np.array([4,5,6])
np.dstack((x,y))
Let x be an array [1, 2, 3, …, 9]. Split x into 3 arrays, each of which has 4, 2, and 3 elements in the original order.
x = np.arange(1,10)
# l = [x[:4],x[4:6],x[6:]]
# l
np.split(x,[4,6])
Let x be an array
[[[ 0., 1., 2., 3.],
[ 4., 5., 6., 7.]],
[[ 8., 9., 10., 11.],
[ 12., 13., 14., 15.]]].
Split it into two such that the first array looks like
[[[ 0., 1., 2.],
[ 4., 5., 6.]],
[[ 8., 9., 10.],
[ 12., 13., 14.]]].
and the second one look like:
[[[ 3.],
[ 7.]],
[[ 11.],
[ 15.]]].
x = np.arange(16).reshape(-1,2,4)
out1 = np.split(x,[3],axis=2)
out_1
三维数组的顺序:页,行,列
Let x be an array [0, 1, 2]. Convert it to
[[0, 1, 2, 0, 1, 2],
[0, 1, 2, 0, 1, 2]].
x = arange(3)
np.tile(x,[2,2])
Q15. Let x be an array [0, 1, 2]. Convert it to
[0, 0, 1, 1, 2, 2].
x=np.arange(3)
np.repeat(x,2)
Q16. Let x be an array [0, 0, 0, 1, 2, 3, 0, 2, 1, 0].
remove the leading the trailing zeros.
x = np.array([0, 0, 0, 1, 2, 3, 0, 2, 1, 0])
a = np.trim_zeros(x,trim ='bf')#参数trim中b代表后面,f代表前面
print(a)
help(np.trim_zeros)
Let x be an array [2, 2, 1, 5, 4, 5, 1, 2, 3]. Get two arrays of unique elements and their counts.
x = np.array([2, 2, 1, 5, 4, 5, 1, 2, 3])
np.unique(x,return_counts=True)