import numpy as np #创建数组(给array函数传递Python序列对象) a = np.array([1,2,3,4,5]) b = np.array((1,2,3,4,5,6)) c = np.array([ [1,2,3,4,5], [6,7,8,9,10] ]) #数组的大小用shape属性获得 print(type(a), a.shape, a, ‘\n‘) print(type(b), b.shape, b,‘\n‘) print(type(c),c.shape, c,‘\n‘) #改变数组的shape属性,改变自身元素排列 c.shape = 2, 5 print(c.shape, c) c.shape = 10, -1 print(c.shape, c) #通过reshape改变数组排序,赋值给新数组,但是共享同一块内存 d = b.reshape((2,3)) print(d.shape, d) b[1]=100 print(b,d) 输出:
<class ‘numpy.ndarray‘> (5,) [1 2 3 4 5]
<class ‘numpy.ndarray‘> (6,) [1 2 3 4 5 6]
<class ‘numpy.ndarray‘> (2, 5) [[ 1 2 3 4 5]
[ 6 7 8 9 10]]
(2, 5) [[ 1 2 3 4 5]
[ 6 7 8 9 10]]
(10, 1) [[ 1]
[ 2]
[ 3]
[ 4]
[ 5]
[ 6]
[ 7]
[ 8]
[ 9]
[10]]
(2, 3) [[1 2 3]
[4 5 6]]
[ 1 100 3 4 5 6] [[ 1 100 3]
[ 4 5 6]]
import numpy as np #创建数组(通过numpy函数) a = np.arange(0, 1, 0.1) #不包括终值 b = np.linspace(0, 1, 10) #包括终值,等差10个数 c = np.logspace(0, 2, 10) #从1到100,等比10个数 s = "abcdef" d = np.fromstring(s, dtype=np.int8) e = np.fromstring(s, dtype=np.int16) print(a,‘\n‘,b,‘\n‘,c,‘\n‘,d,‘\n‘,e,‘\n‘)
输出:
[ 0. 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9]
[ 0. 0.11111111 0.22222222 0.33333333 0.44444444 0.55555556
0.66666667 0.77777778 0.88888889 1. ]
[ 1. 1.66810054 2.7825594 4.64158883 7.74263683
12.91549665 21.5443469 35.93813664 59.94842503 100. ]
[ 97 98 99 100 101 102]
[25185 25699 26213]
import numpy as np #创建10个元素的一维数组 def func(i): return i%4+1 print ( np.fromfunction(func,(10,)) )
输出:
[ 1. 2. 3. 4. 1. 2. 3. 4. 1. 2.]
import numpy as np def func(i,j): return (i + 1) * (j + 1) print(np.fromfunction(func, (9,9)))
输出:
[[ 1. 2. 3. 4. 5. 6. 7. 8. 9.]
[ 2. 4. 6. 8. 10. 12. 14. 16. 18.]
[ 3. 6. 9. 12. 15. 18. 21. 24. 27.]
[ 4. 8. 12. 16. 20. 24. 28. 32. 36.]
[ 5. 10. 15. 20. 25. 30. 35. 40. 45.]
[ 6. 12. 18. 24. 30. 36. 42. 48. 54.]
[ 7. 14. 21. 28. 35. 42. 49. 56. 63.]
[ 8. 16. 24. 32. 40. 48. 56. 64. 72.]
[ 9. 18. 27. 36. 45. 54. 63. 72. 81.]]