程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

python numpy數組

編輯:Python

1.數組創建:

import numpy
arr = numpy.array([11, 22, 33, 44, 55])
print(arr)
輸出:
[11 22 33 44 55]
#數組屬性查看:
print(type(arr))
輸出:
<class 'numpy.ndarray'>

2.數組維度:

import numpy
arr = numpy.array(10)
arr1 = numpy.array([1, 2, 3, 4, 5])
arr2 = numpy.array((1,2,3,4,5))
arr3 = numpy.array([[8,9,10],[1,2,3],[4,5,6]])
#查看維度數:
print(arr)
print(arr1)
print(arr2)
print(arr3)
輸出:
0
1
1
2

3.數組索引:

import numpy
arr = numpy.array([1,2,3,4,5])
arr1 = numpy.array([[11,22],[33,44],[55,66]])
print(arr[3])
輸出:
4
print(arr11[2,1])
輸出:
66

4.數組迭代:

import numpy
arr = numpy.array([11,22,33])
for i in arr:
print(i)
輸出:
11
22
33
arr0 = numpy.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]])
for x in arr0:
print(x)
for y in x:
print(y)
for z in y:
print(z)
輸出:
[1 2 3]
1
2
3
[4 5 6]
4
5
6
[[ 7 8 9]
[10 11 12]]
[7 8 9]
7
8
9
[10 11 12]
10
11
12
for k in numpy.nditer(arr0):
print(k)
輸出:
1
2
3
4
5
6
7
8
9
10
11
12

5.數組隨機取數:

from numpy import random
#整數分3組5個
x = random.randint(100,size=(3,5))
#浮點數分3組5個 
y = random.rand(3,5)
z = random.choice([11,22,33])
print(x)
輸出:
[[83 28 58 86 28]
[74 10 50 64 77]
[74 47 72 52 69]]
print(y)
輸出:
[[0.62403419 0.28132926 0.39252042 0.24294266 0.32071179]
[0.00681339 0.22880091 0.96694071 0.72081899 0.52969825]
[0.89168273 0.44716415 0.97038642 0.39105253 0.58724623]]
print(z)
輸出:
22

6.數組合並:

import numpy
arr8 = numpy.array([[1, 2, 3],[7,8,9]])
arr9 = numpy.array([[4, 5, 6],[10,11,12]])
arr10 = numpy.array([[4, 7, 6],[10,17,12]])
print(numpy.concatenate((arr8,arr9),axis=1))
輸出:
[[ 1 2 3 4 5 6]
[ 7 8 9 10 11 12]]
print(numpy.stack((arr8,arr9),axis=1))
輸出:
[[[ 1 2 3]
[ 4 5 6]]
[[ 7 8 9]
[10 11 12]]]
print(numpy.vstack((arr8,arr9)))
輸出:
[[ 1 2 3]
[ 7 8 9]
[ 4 5 6]
[10 11 12]]
print(numpy.dstack((arr8,arr9)))
輸出:
[[[ 1 4]
[ 2 5]
[ 3 6]]
[[ 7 10]
[ 8 11]
[ 9 12]]]
print(numpy.concatenate((arr8,arr9)))
輸出:
[[ 1 2 3]
[ 7 8 9]
[ 4 5 6]
[10 11 12]]
print(numpy.hstack((arr8,arr9)))
輸出:
[[ 1 2 3 4 5 6]
[ 7 8 9 10 11 12]]

7.數組拆分:

import numpy
arr = numpy.array([1,2,3,4,5,6,7,8])
print(numpy.array_split(arr,2))
輸出:
[array([1, 2, 3, 4]), array([5, 6, 7, 8])]

8.數組過濾、排序:

import numpy
arr = numpy.array([1,2,3,4,5,6,7,8])
new_arr = []
for i in arr:
if i%2 == 0:
new_arr.append(True)
else:
new_arr.append(False)
N_arr = arr[new_arr]
print(new_arr)
print(N_arr)
輸出:
[False, True, False, True, False,rue, False, True]
[2 4 6 8]
arr0 = numpy.array([[4, 7, 6],[10,17,12]])
print(numpy.sort(arr0))
輸出:
[[ 4 6 7]
[10 12 17]]]

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved