站点图标 AI技术聚合

Python之深入解析Numpy的高级操作和使用

一、数组上的迭代

import numpy as np
a = np.arange(0, 60, 5)
a = a.reshape(3, 4)
print(a)
for x in np.nditer(a):
    print(x)
[[ 0  5 10 15]
 [20 25 30 35]
 [40 45 50 55]]
0
5
10
15
20
25
30
35
40
45
50
55
import numpy as np
a = np.arange(0, 60, 5)
a = a.reshape(3, 4)
print(a)
b = np.array([1, 2, 3, 4], dtype=int)
print(b)
for x, y in np.nditer([a, b]):
    print(x, y)
[[ 0  5 10 15]
 [20 25 30 35]
 [40 45 50 55]]
[1 2 3 4]
0 1
5 2
10 3
15 4
20 1
25 2
30 3
35 4
40 1
45 2
50 3
55 4

二、数组形状修改函数

① ndarray.reshape

ndarray.reshape(arr, newshape, order)
import numpy as np
a = np.arange(8)
print(a)
b = a.reshape(4, 2)
print(b)
[0 1 2 3 4 5 6 7]
[[0 1]
 [2 3]
 [4 5]
 [6 7]]

② ndarray.flat

import numpy as np
a = np.arange(0, 16, 2).reshape(2, 4)
print(a)
# 返回展开数组中的下标的对应元素
print(list(a.flat))
[[ 0  2  4  6]
 [ 8 10 12 14]]
[0, 2, 4, 6, 8, 10, 12, 14]

③ ndarray.flatten

ndarray.flatten(order)
import numpy as np
a = np.arange(8).reshape(2, 4)
print(a)
# default is column-major
print(a.flatten())
print(a.flatten(order='F'))
[[0 1 2 3]
 [4 5 6 7]]
[0 1 2 3 4 5 6 7]
[0 4 1 5 2 6 3 7]

三、数组翻转操作函数

① numpy.transpose

numpy.transpose(arr, axes)
import numpy as np
a = np.arange(24).reshape(2, 3, 4)
print(a)
b = np.array(np.transpose(a))
print(b)
print(b.shape)
[[[ 0  1  2  3]
  [ 4  5  6  7]
  [ 8  9 10 11]]

 [[12 13 14 15]
  [16 17 18 19]
  [20 21 22 23]]]
[[[ 0 12]
  [ 4 16]
  [ 8 20]]

 [[ 1 13]
  [ 5 17]
  [ 9 21]]

 [[ 2 14]
  [ 6 18]
  [10 22]]

 [[ 3 15]
  [ 7 19]
  [11 23]]]
(4, 3, 2)
b = np.array(np.transpose(a, (1, 0, 2)))
print(b)
print(b.shape
[[[ 0  1  2  3]
  [12 13 14 15]]

 [[ 4  5  6  7]
  [16 17 18 19]]

 [[ 8  9 10 11]
  [20 21 22 23]]]
(3, 2, 4)

② numpy.ndarray.T

import numpy as np
a = np.arange(12).reshape(3, 4)
print(a)
print(a.T)
[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]]
[[ 0  4  8]
 [ 1  5  9]
 [ 2  6 10]
 [ 3  7 11]]

③ numpy.swapaxes

numpy.swapaxes(arr, axis1, axis2)
import numpy as np
a = np.arange(8).reshape(2, 2, 2)
print(a)
print(np.swapaxes(a, 2, 0))
[[[0 1]
  [2 3]]

 [[4 5]
  [6 7]]]
[[[0 4]
  [2 6]]

 [[1 5]
  [3 7]]]

④ numpy.rollaxis

numpy.rollaxis(arr, axis, start)
import numpy as np
a = np.arange(8).reshape(2,2,2)
print(a)
print(np.rollaxis(a,2))
print(np.rollaxis(a,2,1))
[[[0 1]
  [2 3]]

 [[4 5]
  [6 7]]]
[[[0 2]
  [4 6]]

 [[1 3]
  [5 7]]]
[[[0 2]
  [1 3]]

 [[4 6]
  [5 7]]]

四、数组修改维度函数

① numpy.broadcast_to

numpy.broadcast_to(array, shape, subok)
import numpy as np
a = np.arange(4).reshape(1,4)
print(a)
print(np.broadcast_to(a,(4,4)))
[[0 1 2 3]]
[[0 1 2 3]
 [0 1 2 3]
 [0 1 2 3]
 [0 1 2 3]]

② numpy.expand_dims

numpy.expand_dims(arr, axis)
import numpy as np
x = np.array(([1, 2], [3, 4]))
print(x)
y = np.expand_dims(x, axis=0)
print(y)
print(x.shape, y.shape)
y = np.expand_dims(x, axis=1)
print(y)
print(x.ndim, y.ndim)
print(x.shape, y.shape)
[[1 2]
 [3 4]]
[[[1 2]
  [3 4]]]
(2, 2) (1, 2, 2)
[[[1 2]]

 [[3 4]]]
2 3
(2, 2) (2, 1, 2)

③ numpy.squeeze

numpy.squeeze(arr, axis)
import numpy as np
x = np.arange(9).reshape(1, 3, 3)
print(x)
y = np.squeeze(x)
print(y)
print(x.shape, y.shape)
[[[0 1 2]
  [3 4 5]
  [6 7 8]]]
[[0 1 2]
 [3 4 5]
 [6 7 8]]
(1, 3, 3) (3, 3)

五、数组的连接操作

① numpy.stack

numpy.stack(arrays, axis)
import numpy as np
a = np.array([[1,2],[3,4]])
print(a)
b = np.array([[5,6],[7,8]])
print(b)
print(np.stack((a,b),0))
print(np.stack((a,b),1))
[[1 2]
 [3 4]]
[[5 6]
 [7 8]]
[[[1 2]
  [3 4]]

 [[5 6]
  [7 8]]]
[[[1 2]
  [5 6]]

 [[3 4]
  [7 8]]]

② numpy.hstack

import numpy as np
a = np.array([[1, 2], [3, 4]])
print(a)
b = np.array([[5, 6], [7, 8]])
print(b)
print('水平堆叠:')
c = np.hstack((a, b))
print(c)
[[1 2]
 [3 4]]
[[5 6]
 [7 8]]
水平堆叠:
[[1 2 5 6]
 [3 4 7 8]]

③ numpy.vstack

import numpy as np
a = np.array([[1, 2], [3, 4]])
print(a)
b = np.array([[5, 6], [7, 8]])
print(b)
print('竖直堆叠:')
c = np.vstack((a, b))
print(c)
[[1 2]
 [3 4]]
[[5 6]
 [7 8]]
竖直堆叠:
[[1 2]
 [3 4]
 [5 6]
 [7 8]]

④ numpy.concatenate

numpy.concatenate((a1, a2, …), axis)
import numpy as np
a = np.array([[1,2],[3,4]])
print(a)
b = np.array([[5,6],[7,8]])
print(b)
print(np.concatenate((a,b)))
print(np.concatenate((a,b),axis = 1))
[[1 2]
 [3 4]]
[[5 6]
 [7 8]]
[[1 2]
 [3 4]
 [5 6]
 [7 8]]
[[1 2 5 6]
 [3 4 7 8]]

六、数组的分割操作

① numpy.split

numpy.split(ary, indices_or_sections, axis)
import numpy as np
a = np.arange(9)
print(a)
print('将数组分为三个大小相等的子数组:')
b = np.split(a,3)
print(b)
print('将数组在一维数组中表明的位置分割:')
b = np.split(a,[4,7])
print(b)
[0 1 2 3 4 5 6 7 8]
将数组分为三个大小相等的子数组:
[array([0, 1, 2]), 
array([3, 4, 5]), 
array([6, 7, 8])]
将数组在一维数组中表明的位置分割:
[array([0, 1, 2, 3]), 
array([4, 5, 6]), 
array([7, 8])]

② numpy.hsplit

import numpy as np
a = np.arange(16).reshape(4,4)
print(a)
print('水平分割:')
b = np.hsplit(a,2)
print(b)
[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]
 [12 13 14 15]]
水平分割:
[array([[ 0,  1],
       [ 4,  5],
       [ 8,  9],
       [12, 13]]), 
 array([[ 2,  3],
       [ 6,  7],
       [10, 11],
       [14, 15]])]

③ numpy.vsplit

import numpy as np
a = np.arange(16).reshape(4,4)
print(a)
print('竖直分割:')
b = np.vsplit(a,2)
print(b)
[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]
 [12 13 14 15]]
竖直分割:
[array([[0, 1, 2, 3],
       [4, 5, 6, 7]]),
 array([[ 8,  9, 10, 11],
       [12, 13, 14, 15]])]

七、数组元素操作

① numpy.resize

numpy.resize(arr, shape)
import numpy as np
a = np.array([[1,2,3],[4,5,6]])
print(a)
print(a.shape)
b = np.resize(a, (3,2))
print(b)
print(b.shape)
print('修改第二个数组的大小:')
b = np.resize(a,(3,3))
print(b)
print('修改第三个数组的大小:')
b = np.resize(a,(2,2))
print(b)
[[1 2 3]
 [4 5 6]]
(2, 3)
[[1 2]
 [3 4]
 [5 6]]
(3, 2)
修改第二个数组的大小:
[[1 2 3]
 [4 5 6]
 [1 2 3]]
修改第三个数组的大小:
[[1 2]
 [3 4]]

② numpy.append

numpy.append(arr, values, axis)
import numpy as np
a = np.array([[1,2,3],[4,5,6]])
print(a)
print(np.append(a, [[7,8,9]],axis = 0))
print(np.append(a, [[5,5,5],[7,8,9]],axis = 1))
[[1 2 3]
 [4 5 6]]
[[1 2 3]
 [4 5 6]
 [7 8 9]]
[[1 2 3 5 5 5]
 [4 5 6 7 8 9]]

③ numpy.insert

numpy.insert(arr, obj, values, axis)
import numpy as np
a = np.array([[1,2],[3,4],[5,6]])
print(a)
print(np.insert(a,3,[11,12]))
print(np.insert(a,1,[11],axis = 0))
print(np.insert(a,1,[11],axis = 1))
[[1 2]
 [3 4]
 [5 6]]
[ 1  2  3 11 12  4  5  6]
[[ 1  2]
 [11 11]
 [ 3  4]
 [ 5  6]]
[[ 1 11  2]
 [ 3 11  4]
 [ 5 11  6]]

④ numpy.delete

Numpy.delete(arr, obj, axis)
import numpy as np
a = np.array([[1,2],[3,4],[5,6]])
print(a)
print(np.delete(a,5))
print(np.delete(a,1,axis = 1))
[[1 2]
 [3 4]
 [5 6]]
[1 2 3 4 5]
[[1]
 [3]
 [5]]

⑤ numpy.unique

numpy.unique(arr, return_index, return_inverse, return_counts)
import numpy as np
a = np.array([5,2,6,2,7,5,6,8,2,9])
u = np.unique(a)
print(u)
u,indices = np.unique(a, return_index = True)
print(u, indices)
u,indices = np.unique(a,return_inverse = True)
print(u, indices)
u,indices = np.unique(a,return_counts = True)
print(u, indices)
[2 5 6 7 8 9][2 5 6 7 8 9] 
[1 0 2 4 7 9][2 5 6 7 8 9] 
[1 0 2 0 3 1 2 4 0 5][2 5 6 7 8 9] 
[3 2 2 1 1 1]

八、NumPy 字符串函数

import numpy as np
print(np.char.add(['hello'],[' xyz']))
print(np.char.add(['hello', 'hi'],[' abc', ' xyz']))
print(np.char.multiply('Hello ',3))
print(np.char.center('hello', 20,fillchar = '*'))
print(np.char.capitalize('hello world'))
print(np.char.title('hello how are you?'))
print(np.char.lower(['HELLO','WORLD']))
print(np.char.lower('HELLO'))
print(np.char.upper('hello'))
print(np.char.upper(['hello','world']))
print(np.char.split ('hello how are you?'))
print(np.char.split ('YiibaiPoint,Hyderabad,Telangana', sep = ','))
print(np.char.splitlines('hello\nhow are you?'))
print(np.char.splitlines('hello\rhow are you?'))
print(np.char.strip('ashok arora','a'))
print(np.char.strip(['arora','admin','java'],'a'))
print(np.char.join(':','dmy'))
print(np.char.join([':','-'],['dmy','ymd']))
print(np.char.replace ('He is a good boy', 'is', 'was'))
a = np.char.encode('hello', 'cp500')
print(a)
print(np.char.decode(a,'cp500'))
['hello xyz']
['hello abc' 'hi xyz']
Hello Hello Hello 
*******hello********
Hello world
Hello How Are You?
['hello' 'world']
hello
HELLO
['HELLO' 'WORLD']
['hello', 'how', 'are', 'you?']
['YiibaiPoint', 'Hyderabad', 'Telangana']
['hello', 'how are you?']
['hello', 'how are you?']
shok aror
['ror' 'dmin' 'jav']
d:m:y
['d:m:y' 'y-m-d']
He was a good boy
b'\x88\x85\x93\x93\x96'
hello

九、NumPy 算数函数

① NumPy 三角函数

import numpy as np
a = np.array([0,30,45,60,90])
# 通过乘 pi/180 转化为弧度
print(np.sin(a*np.pi/180))
print(np.cos(a*np.pi/180))
print(np.tan(a*np.pi/180))
[ 0.          0.5         0.70710678  0.8660254   1.        ]
[  1.00000000e+00   8.66025404e-01   7.07106781e-01   5.00000000e-01
   6.12323400e-17]
[  0.00000000e+00   5.77350269e-01   1.00000000e+00   1.73205081e+00
   1.63312394e+16]

② NumPy 舍入函数

import numpy as np
a = np.array([1.0, 5.55, 123, 0.567, 25.532])
print(np.around(a))
print(np.around(a, decimals=1))
print(np.floor(a))
print(np.ceil(a))
[   1.    6.  123.    1.   26.]
[   1.     5.6  123.     0.6   25.5]
[   1.    5.  123.    0.   25.]
[   1.    6.  123.    1.   26.]

③ NumPy 算数运算

import numpy as np
a = np.array([0.25, 2, 1, 0.2, 100])
print(np.reciprocal(a))
print(np.power(a,2))
a = np.array([10,20,30])
b = np.array([3,5,7])
print(np.mod(a,b))
[ 4.    0.5   1.    5.    0.01]
[  6.25000000e-02   4.00000000e+00   1.00000000e+00
   4.00000000e-02.  1.00000000e+04]
[1 0 2]

④ NumPy 统计函数

import numpy as np
a = np.array([[3,7,5],[8,4,3],[2,4,9]])
print(np.amin(a,1))
print(np.amax(a,1))
print(np.ptp(a))
print(np.percentile(a,50))
print(np.median(a))
print(np.mean(a))
print(np.average(a))
print(np.std([1,2,3,4])) #返回数组标准差
print(np.var([1,2,3,4])) #返回数组方差
[3 3 2]
[7 8 9]
7
4.0
4.0
5.0
5.0
1.11803398875
1.25

十、排序、搜索和计数函数

import numpy as np
a = np.array([[3, 7, 3, 1], [9, 7, 8, 7]])
print(np.sort(a))
print(np.argsort(a))
print(np.argmax(a))
print(np.argmin(a))
print(np.nonzero(a))
print(np.where(a > 3))
nm = ('raju', 'anil', 'ravi', 'amar')
dv = ('f.y.', 's.y.', 's.y.', 'f.y.')
print(np.lexsort((dv, nm)))
[[1 3 3 7]
 [7 7 8 9]]
[[3 0 2 1]
 [1 3 2 0]]
4
3
(array([0, 0, 0, 0, 1, 1, 1, 1], dtype=int64), 
array([0, 1, 2, 3, 0, 1, 2, 3], dtype=int64))
(array([0, 1, 1, 1, 1], dtype=int64), 
array([1, 0, 1, 2, 3], dtype=int64))
[3 1 0 2]

十一、IO 文件操作

import numpy as np
a = np.array([1,2,3,4,5])
np.save('outfile',a)
b = np.load('outfile.npy')
print(b)
a = np.array([1,2,3,4,5])
np.savetxt('out.txt',a)
b = np.loadtxt('out.txt')
print(b)
[1 2 3 4 5]
[ 1.  2.  3.  4.  5.]

文章出处登录后可见!

已经登录?立即刷新
退出移动版