从菜鸟教程复制过来的,
转载地址:https://www.runoob.com/numpy/numpy-array-creation.html
1.创建未初始化的narray数组
格式如下:
numpy.empty(shape=, dtype=, order=)
示例:
mport numpy as np
x = np.empty([3,2], dtype = int)
print (x)
结果如下:
[[ 6917529027641081856 5764616291768666155]
[ 6917529027641081859 -5764598754299804209]
[ 4497473538 844429428932120]]
2.创建0数组,元素全部为0
格式:numpy.zeros(shap, dtype, order)
示例:
import numpy as np
# 默认为浮点数
x = np.zeros(5)
print(x)
# 设置类型为整数
y = np.zeros((5,), dtype = np.int)
print(y)
# 自定义类型
z = np.zeros((2,2), dtype = [('x', 'i4'), ('y', 'i4')])
print(z)
结果如下:
[0. 0. 0. 0. 0.]
[0 0 0 0 0]
[[(0, 0) (0, 0)]
[(0, 0) (0, 0)]]
3.创建元素全为1的数组:
格式:
numpy.ones(shape, dtype, order)
示例:
import numpy as np
# 默认为浮点数
x = np.ones(5)
print(x)
# 自定义类型
x = np.ones([2,2], dtype = int)
print(x)
4.从列表或元祖中创建narray数组
numpy.asarray(a, dtype = None, order = None)
1.将列表转为数组:
import numpy as np
x = [1,2,3]
a = np.array(x)
print (a)
2.将元组转为数组:
import numpy as np
x = (1,2,3)
a = np.array(x)
print (a)
结果如下:
[1 2 3]
5.从数值范围创建数组:
格式:
numpy.arange(start, stop, step, dtype)
示例:
import numpy as np
x = np.arange(5)
print (x)
结果如下:
[0 1 2 3 4]
6.创建等差和等比数组
- .等差数组:
格式:
np.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None)
示例1:
import numpy as np
a = np.linspace(1,10,10)
print(a)
结果:
[ 1. 2. 3. 4. 5. 6. 7. 8. 9. 10.]
示例2:endpoint为False的情况
-
等比数组:
格式:
np.logspace(start, stop, num=50, endpoint=True, base=10.0, dtype=None)
示例1:
import numpy as np
# 默认底数是 10
a = np.logspace(1.0, 2.0, num = 10)
print (a)
结果如下;
[ 10. 12.91549665 16.68100537 21.5443469 27.82559402
35.93813664 46.41588834 59.94842503 77.42636827 100. ]
示例2:将对数的底数设置为 2 :
import numpy as np
a = np.logspace(0,9,10,base=2)
print (a)
[ 1. 2. 4. 8. 16. 32. 64. 128. 256. 512.]