这里简单地介绍一下 numpy
模块中的 reduce()
函数的用法.
代码如下:
# -*- coding: utf-8 -*-
import numpy as np
class Debug:
def __init__(self):
self.array1 = np.array([1, 2, 3, 4])
self.array2 = np.array([5, 6, 7, 8])
self.array3 = np.array([[1, 2, 3, 4], [5, 6, 7, 8]])
def mainProgram(self):
result = np.add(self.array1, self.array2)
print("The value of result is: ")
print(result)
result1 = np.add.reduce(self.array3, axis=0)
print("The value of result1 is: ")
print(result1)
result2 = np.add.reduce(self.array3, axis=1)
print("The value of result2 is: ")
print(result2)
if __name__ == '__main__':
main = Debug()
main.mainProgram()
"""
The value of result is:
[ 6 8 10 12]
The value of result1 is:
[ 6 8 10 12]
The value of result2 is:
[10 26]
"""
我们可以看到,当我们指定坐标轴为 axis=0
时,np.add.reduce()
函数会将数组沿着 y
轴加起来,当指定坐标轴 axis=1
时,np.add.reduce()
函数会将数组沿着 x
轴加起来。对于为什么是这样,可以参考np.repeat()的坐标轴问题。
如果大家觉得有用,请高抬贵手给一个赞让我上推荐让更多的人看到吧~