python利用numpy创建数组(等比,等差,空数组,1数组)
生活随笔
收集整理的這篇文章主要介紹了
python利用numpy创建数组(等比,等差,空数组,1数组)
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
從菜鳥教程復(fù)制過來的,
轉(zhuǎn)載地址:https://www.runoob.com/numpy/numpy-array-creation.html
1.創(chuàng)建未初始化的narray數(shù)組
格式如下:
numpy.empty(shape=, dtype=, order=)示例:
mport numpy as np x = np.empty([3,2], dtype = int) print (x) 結(jié)果如下: [[ 6917529027641081856 5764616291768666155][ 6917529027641081859 -5764598754299804209][ 4497473538 844429428932120]]?
2.創(chuàng)建0數(shù)組,元素全部為0
格式:numpy.zeros(shap, dtype, order)
示例:
import numpy as np# 默認(rèn)為浮點(diǎn)數(shù) x = np.zeros(5) print(x)# 設(shè)置類型為整數(shù) y = np.zeros((5,), dtype = np.int) print(y)# 自定義類型 z = np.zeros((2,2), dtype = [('x', 'i4'), ('y', 'i4')]) print(z)結(jié)果如下:
[0. 0. 0. 0. 0.] [0 0 0 0 0] [[(0, 0) (0, 0)][(0, 0) (0, 0)]]?
3.創(chuàng)建元素全為1的數(shù)組:
格式:
numpy.ones(shape, dtype, order)
示例:
import numpy as np# 默認(rèn)為浮點(diǎn)數(shù) x = np.ones(5) print(x)# 自定義類型 x = np.ones([2,2], dtype = int) print(x)?
4.從列表或元祖中創(chuàng)建narray數(shù)組
numpy.asarray(a, dtype = None, order = None)1.將列表轉(zhuǎn)為數(shù)組:
import numpy as np x = [1,2,3] a = np.array(x) print (a)2.將元組轉(zhuǎn)為數(shù)組:
import numpy as np x = (1,2,3) a = np.array(x) print (a) 結(jié)果如下: [1 2 3]?
5.從數(shù)值范圍創(chuàng)建數(shù)組:
格式:
numpy.arange(start, stop, step, dtype)示例:
import numpy as npx = np.arange(5) print (x)結(jié)果如下:
[0 1 2 3 4]?
6.創(chuàng)建等差和等比數(shù)組
- .等差數(shù)組:
格式:
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)結(jié)果:
[ 1. 2. 3. 4. 5. 6. 7. 8. 9. 10.]示例2:endpoint為False的情況
?
?
-
等比數(shù)組:
格式:
np.logspace(start, stop, num=50, endpoint=True, base=10.0, dtype=None)示例1:
import numpy as np # 默認(rèn)底數(shù)是 10 a = np.logspace(1.0, 2.0, num = 10) print (a)結(jié)果如下;
[ 10. 12.91549665 16.68100537 21.5443469 27.82559402 35.93813664 46.41588834 59.94842503 77.42636827 100. ]示例2:將對數(shù)的底數(shù)設(shè)置為 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.]?
總結(jié)
以上是生活随笔為你收集整理的python利用numpy创建数组(等比,等差,空数组,1数组)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: linux如何使用vim显示行号语法高亮
- 下一篇: windows10 + Anaconda