如何在 NumPy 中设置行和列的轴?
在本文中,我们将看到如何在 NumPy 中设置行和列的轴。
使用的功能
- np.array(object):创建一个NumPy数组,对象是包含数组的参数
- np.reshape(rows, columns):将数组重塑为指定的行数和列数。在下面的例子中,我们用 -1 代替行,让 numpy 判断每行是否有 3 列。
- np.sum(axis):计算元素的总和或相加。在这里,我们提到了根据需要执行阵列、行或列操作的轴。
示例 1:为数组计算设置轴
在这个例子中,我们将把 NumPy 数组重塑为每行 3 列的行,即 nparray.reshape(-1, 3) 使其成为二维的。然后我们将按照从 NumPy 数组的第一个元素到最后一个元素的正常顺序对数组元素进行数组元素的求和运算。我们专门设置axis= None 来触发正常的array-wise 操作。
代码:
Python3
import numpy as np
nparray = np.array([[1, 2, 3], [11, 22, 33],
[4, 5, 6], [8, 9, 10],
[20, 30, 40]])
nparray = nparray.reshape(-1, 3)
print(nparray)
# calculating sum along
# axix=None i.e array-wise
output = nparray.sum(axis=None)
print("\n\nSum array-wise: ", output)
Python3
import numpy as np
nparray = np.array([[1, 2, 3], [11, 22, 33],
[4, 5, 6], [8, 9, 10],
[20, 30, 40]])
nparray = nparray.reshape(-1, 3)
print(nparray)
# calculating sum along axix=0
# i.e column-wise
output = nparray.sum(axis = 0)
print("\n\nSum column-wise: ", output)
Python3
import numpy as np
nparray = np.array([[1, 2, 3], [11, 22, 33],
[4, 5, 6], [8, 9, 10],
[20, 30, 40]])
nparray = nparray.reshape(-1, 3)
print(nparray)
# calculating sum along axix=1
# i.e row0wise
output = nparray.sum(axis = 1)
print("\n\nSum row-wise: ", output)
输出 :
[[ 1 2 3]
[11 22 33]
[ 4 5 6]
[ 8 9 10]
[20 30 40]]
Sum array-wise: 204
示例 2:为按列计算设置轴
在这个例子中,我们将把 numpy 数组重塑为每行 3 列的行。然后使用 sum()函数逐列执行数组元素的求和运算。我们专门设置axis= 0 来触发正常的array-wise 操作。
代码:
蟒蛇3
import numpy as np
nparray = np.array([[1, 2, 3], [11, 22, 33],
[4, 5, 6], [8, 9, 10],
[20, 30, 40]])
nparray = nparray.reshape(-1, 3)
print(nparray)
# calculating sum along axix=0
# i.e column-wise
output = nparray.sum(axis = 0)
print("\n\nSum column-wise: ", output)
输出 :
[[ 1 2 3]
[11 22 33]
[ 4 5 6]
[ 8 9 10]
[20 30 40]]
Sum column-wise: [44 68 92]
示例 3:为行式计算设置轴
我们会专门设置axis = 1来触发正常的row-wise计算。
代码:
蟒蛇3
import numpy as np
nparray = np.array([[1, 2, 3], [11, 22, 33],
[4, 5, 6], [8, 9, 10],
[20, 30, 40]])
nparray = nparray.reshape(-1, 3)
print(nparray)
# calculating sum along axix=1
# i.e row0wise
output = nparray.sum(axis = 1)
print("\n\nSum row-wise: ", output)
输出 :
[[ 1 2 3]
[11 22 33]
[ 4 5 6]
[ 8 9 10]
[20 30 40]]
Sum row-wise: [ 6 66 15 27 90]