首页
学习
活动
专区
圈层
工具
发布

Python科学计算库numpy中的add运算

闲言碎语不多讲,直接上代码。

>>> import numpy as np

>>> np.add.accumulate([1,2,3]) # 累加

array([1, 3, 6], dtype=int32)

>>> np.add.accumulate([1,2,3,4,5])

array([ 1, 3, 6, 10, 15], dtype=int32)

>>> np.add.reduce([1,2,3,4,5]) # 连加

15

>>> x = np.array([1,2,3,4])

>>> np.add.at(x, [0,2], 3) # 下标0和2的元素分别加3

>>> x

array([4, 2, 6, 4])

>>> np.add.outer([1,2,3], [4,5,6])

array([[5, 6, 7], # 1+4, 1+5, 1+6

[6, 7, 8], # 2+4, 2+5, 2+6

[7, 8, 9]]) # 3+4, 3+5, 3+6

>>> np.add.outer([1,2,3], [4,5,6,7])

array([[ 5, 6, 7, 8],

[ 6, 7, 8, 9],

[ 7, 8, 9, 10]])

>>> np.add.outer([1,2,3,4], [5,6,7])

array([[ 6, 7, 8],

[ 7, 8, 9],

[ 8, 9, 10],

[ 9, 10, 11]])

>>> np.add.reduceat(np.arange(8),[0,4, 1,5, 2,6, 3,7])

array([ 6, 4, 10, 5, 14, 6, 18, 7], dtype=int32)

>>> x = np.linspace(0, 15, 16).reshape(4,4)

>>> x

array([[ 0., 1., 2., 3.],

[ 4., 5., 6., 7.],

[ 8., 9., 10., 11.],

[ 12., 13., 14., 15.]])

>>> np.add.reduceat(x, [0, 3, 0])

array([[ 12., 15., 18., 21.], # row0+row1+row2

[ 12., 13., 14., 15.], # row3

[ 24., 28., 32., 36.]]) # row0+row1+row2+row3

>>> np.add.reduceat(x, [0, 3, 1])

array([[ 12., 15., 18., 21.], # row0+row1+row2

[ 12., 13., 14., 15.], # row3

[ 24., 27., 30., 33.]]) # row1+row2+row3

>>> np.add.reduceat(x, [0, 3, 2])

array([[ 12., 15., 18., 21.], # row0+row1+row2

[ 12., 13., 14., 15.], # row3

[ 20., 22., 24., 26.]]) # row2+row3

>>> np.add.reduceat(x, [0, 3, 3])

array([[ 12., 15., 18., 21.], # row0+row1+row2

[ 12., 13., 14., 15.], # row3

[ 12., 13., 14., 15.]]) # row3

>>> np.add.reduceat(x, [0, 3, 1, 0])

array([[ 12., 15., 18., 21.], # row0+row1+row2

[ 12., 13., 14., 15.], # row3

[ 4., 5., 6., 7.], # row1

[ 24., 28., 32., 36.]]) # row0+row1+row2+row3

>>> np.add.reduceat(x, [0, 3, 1, 1])

array([[ 12., 15., 18., 21.], # row0+row1+row2

[ 12., 13., 14., 15.], # row3

[ 4., 5., 6., 7.], # row1

[ 24., 27., 30., 33.]]) # row1+row2+row3

>>> np.add.reduceat(x, [0, 3, 1, 2])

array([[ 12., 15., 18., 21.], # row0+row1+row2

[ 12., 13., 14., 15.], # row3

[ 4., 5., 6., 7.], # row1

[ 20., 22., 24., 26.]]) # row2+row3

>>> np.add.reduceat(x, [0, 3, 1, 3])

array([[ 12., 15., 18., 21.], # row0+row1+row2

[ 12., 13., 14., 15.], # row3

[ 12., 14., 16., 18.], # row1

[ 12., 13., 14., 15.]]) # row3

>>> np.add.reduceat(x, [0, 3, 1, 3], axis=1) # 对列进行计算

array([[ 3., 3., 3., 3.],

[ 15., 7., 11., 7.],

[ 27., 11., 19., 11.],

[ 39., 15., 27., 15.]])

下一篇
举报
领券