numpy Python:打印x沿着axes 0和1的累积和

gdx19jrr  于 2023-03-30  发布在  Python
关注(0)|答案(2)|浏览(186)

创建一个x形(5,6)的数组,其中有30个在-30和30之间的随机整数

print the cumulative sum of x along axies 0

print the cumulative sum of x along axies 1

期望的输出是9和-32。
我尝试了下面的代码

import numpy as np
 np.random.seed(100)
 l1= np.random.randint(-30,30, size=(5,6))
 x= np.array(l1)
 print(x.sum(axis=0))
 print(x.sum(axis=1))

能告诉我这是怎么回事吗?

wfypjpf4

wfypjpf41#

表达式的结果是:

x.sum(axis=0)  ==  array([ -9, -58, -38,  40,  16,   9])
x.sum(axis=1)  ==  array([-68,  47,   1,  12, -32])

正如你所写的,预期结果是 9-32,也许你想计算最后一列最后一行的总和?
为了得到这些结果,计算:

x[:, -1].sum()    (yields 9)
x[-1, :].sum()    (yiels -32)
93ze6v8z

93ze6v8z2#

import numpy as np
def array_oper(num1,num2):

np.random.seed(100)
x = np.random.randint(num1, num2+1, size=(5, 6))
cumsum_axis0 = np.cumsum(x, axis=0)
print(cumsum_axis0[0][-1])
cumsum_axis1 = np.cumsum(x, axis=1)
print(cumsum_axis1[:,0][-1])

相关问题