#numpy中reshape的实例
作者:冯德平(山野雪人)
2021-11-29
import numpy as np
#numpy.arange(n).reshape(a, b); 依次生成n个自然数,并且以a行b列的数组形式显示:
z=np.arange(12).reshape(2,6)
print(z)
'''
显示结果:
[[ 0 1 2 3 4 5]
[ 6 7 8 9 10 11]]
'''
#z=np.arange(a).reshape(c,-1) #注意a/c应为整数,要不然会产生错误,行数为c行,列需要计算
z=np.arange(14).reshape(7,-1) #指定7行,自动计算列数,如果将7改成8会产生错误
print(z)
'''
显示结果:
[[ 0 1]
[ 2 3]
[ 4 5]
[ 6 7]
[ 8 9]
[10 11]
[12 13]
'''
#reshape(-1, e),列数固定,行需要计算
z=np.arange(14).reshape(-1,7) #同样将7改成8会产生错误,因为14/8结果不是整数
print(z)
'''
显示结果:
[[ 0 1 2 3 4 5 6]
[ 7 8 9 10 11 12 13]]
'''
print("===================")
z=np.linspace(-3,3,4).reshape(-1,1) #将-3与3分成3等份
print(z)
'''
显示结果:
===================
[[-3.]
[-1.]
[ 1.]
[ 3.]]
'''
z=np.linspace(1,17,9).reshape(-1,1) #将1至17等分成8等份,即用9个数表述,后面的-1表示固定行;列为1
print("+++++++++++++++")
print(z)
'''
显示结果:
+++++++++++++++
[[ 1.]
[ 3.]
[ 5.]
[ 7.]
[ 9.]
[11.]
[13.]
[15.]
[17.]]
'''
z=np.linspace(1,17,9,retstep=True)
print("-------------------")
print(z)
'''
结果显示:
-------------------
(array([ 1., 3., 5., 7., 9., 11., 13., 15., 17.]), 2.0)
'''
z=np.linspace(1,17,9,retstep=False)
print("********************")
print(z)
'''
结果显示:
********************
[ 1. 3. 5. 7. 9. 11. 13. 15. 17.]
参考:
https://blog.csdn.net/qq_39432161/article/details/84673127
https://blog.csdn.net/W_weiying/article/details/82112337
'''