简体   繁体   English

numpy-与array.sum相反(减法?)

[英]numpy - opposite of array.sum (subtraction?)

I was wondering if there a method that can subtract values? 我想知道是否有一种可以减去值的方法? Something similar to sum sum类似

for Examples 举些例子

> np.array([[10, 2], [1, 2]]).sum() 
15
" imaginary method "
> np.array([[10, 2], [1, 2]]).sub() 
6

# axis = 1
> np.array([[10, 2], [1, 2]]).sum(axis=1)
array([12,  3])
" imaginary method "
> np.array([[10, 2], [1, 2]]).sum(axis=1)
array([8,  -1])

# axis = 0
> np.array([[10, 2], [1, 2]]).sum(axis=0)
array([11,  4])
"imaginary"
> np.array([[10, 2], [1, 2]]).sub(axis=0)
array([9,  0])

I am frustrated I cann't find anything in docs (somehow numpy docs are not easy to use if you don't know what you looking for). 我很沮丧,我在文档中找不到任何东西(如果您不知道要查找的内容,那么numpy文档就不容易使用)。

thank you. 谢谢。

The difference equivalent of np.sum() is np.diff() np.sum()的等np.diff()np.diff()

Docs 文件

np.sum is np.add.reduce : np.sumnp.add.reduce

In [87]: np.add.reduce(arr, axis=0)                                             
Out[87]: array([11,  4])
In [88]: np.add.reduce(arr, axis=1)                                             
Out[88]: array([12,  3])

There is a subtract ufunc too: 也有一个subtract ufunc

In [93]: np.subtract.reduce(arr, axis=0)                                        
Out[93]: array([9, 0])
In [94]: np.subtract.reduce(arr, axis=1)                                        
Out[94]: array([ 8, -1])

np.diff does sliced subtraction: np.diff会进行切片减法:

In [97]: np.subtract(arr[:-1,:], arr[1:,:])                                     
Out[97]: array([[9, 0]])
In [98]: np.subtract(arr[:,:-1], arr[:,1:])                                     
Out[98]: 
array([[ 8],
       [-1]])

For two elements diff and subtract.reduce do the same thing. 对于两个元素, diffsubtract.reduce做同样的事情。 What's supposed to happen when you have more than 2 rows or columns? 当您有多于2行或2列时,应该怎么办?

In [109]: arr = np.array([[10, 2, 3], [1, 2, 4], [0, 1, 2]])                    
In [110]: arr                                                                   
Out[110]: 
array([[10,  2,  3],
       [ 1,  2,  4],
       [ 0,  1,  2]])

diff does pair wise subtraction, row 0 from 1, row 1 from 2: diff成对减法,第1行第0行,第2行第1行:

In [111]: np.diff(arr, axis=0)                                                  
Out[111]: 
array([[-9,  0,  1],
       [-1, -1, -2]])

subtract.reduce does a cumulative, which might be easier to follow with the accumulate alternative: subtract.reduce .reduce进行累加,使用accumulate替代可能更容易遵循:

In [112]: np.subtract.reduce(arr, axis=0)                                       
Out[112]: array([ 9, -1, -3])
In [113]: np.subtract.accumulate(arr, axis=0)                                   
Out[113]: 
array([[10,  2,  3],
       [ 9,  0, -1],
       [ 9, -1, -3]])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM