赞
踩
import numpy as np
data1 = [6, 7.5, 8, 0, 1]
arr1 = np.array(data1)
print(arr1)
[6. 7.5 8. 0. 1. ]
import numpy as np
data1 = [[6, 7.5, 8, 0, 1], [3.2, 3, 7, 52, 23.4]]
arr1 = np.array(data1)
print(arr1.shape, arr1.ndim, arr1.dtype)
(2, 5) 2 float64
import numpy as np
arr1=np.array([1,2,3,4,5,6])
arr1=arr1.reshape(2,3)
print(arr1)
[[1 2 3]
[4 5 6]]
from numpy import array
array([0.,0.,0.,0.,0.])
array([0., 0., 0., 0., 0.])
np.ones(6)
array([1., 1., 1., 1., 1., 1.])
创建初始值为0,终值为1,步长为0.1的等差数组
np.arange(0,1,0.1)
array([0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9])
创建初始值为0,终值为1,元素个数为10的等差数组
np.linspace(0,1,10)
array([0. , 0.11111111, 0.22222222, 0.33333333, 0.44444444,
0.55555556, 0.66666667, 0.77777778, 0.88888889, 1. ])
创建从100到102,共5个元素的等比数列
np.logspace(0,2,5)
array([ 1. , 3.16227766, 10. , 31.6227766 ,
100. ])
numpy.random.rand(d0, d1, …, dn):生成一个[0,1)之间的随机浮点数或N维浮点数组。
生成2行3列的随机数数组,值在[0,1)之间
np.random.rand(2, 3)
array([[0.95037869, 0.973173 , 0.98286249],
[0.69060825, 0.96183338, 0.75928584]])
numpy.random.randn(d0, d1, …, dn):生成一个浮点数或N维浮点数组,取数范围:正态分布的随机样本数。
生成2行3列的随机数数组,值为正态分布的随机样本数
np.random.randn(2, 3)
array([[ 0.66686711, -0.27895588, -2.02200514],
[ 1.09895485, -2.01676474, -0.48062357]])
numpy.random.randint(low, high=None, size=None, dtype=‘l’):生成一个整数或N维整数数组,取数范围:若high不为None时,取[low,high)之间随机整数,否则取值[0,low)之间随机整数。
生成包含10个元素的值在[0,100) 的数组
np.random.randint(0, 100, 10)
array([55, 28, 53, 59, 27, 71, 17, 5, 21, 92])
生成2*3维的值在[0,100) 的数组
np.random.randint(0, 100, (2,3))
array([[65, 37, 72],
[26, 70, 38]])
r1 = np.random.normal(100, 10, (4, 3))
r2 = np.random.uniform(10, 20, (4, 3))
r3 = np.random.poisson(2.0, (4, 3))
print(r1)
print(r2)
print(r3)
[[119.49006926 99.6777342 96.15609946]
[103.14035375 102.52023622 110.05252578]
[ 98.78937596 92.52315827 120.20142524]
[ 88.41005568 115.13081429 100.10488106]]
[[15.33053313 12.79943738 19.29833314]
[18.48326387 13.64978122 14.29641824]
[11.3836399 10.13409011 11.9494954 ]
[11.30621185 10.75063446 13.64733945]]
[[2 2 1]
[0 2 1]
[1 2 1]
[4 3 6]]
从文本文件构造数组
将数组写入文本文件
np.savetxt('1.txt', arr1, fmt='%0.4f', delimiter=',')
用下标访问元素
x = np.array([1, 2, 3, 4, 5, 6])
print(x[4])
5
x=np.array([[1,2,3],[4,5,6]])
print(x[1])
[4 5 6]
arr=np.arange(10)
print(arr)
print(arr[5:8])
arr[5:8]=12
print
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。