从B的所有元素中减去数组A的所有元素? [英] Subracting all elements of array A from all elements of B?

查看:83
本文介绍了从B的所有元素中减去数组A的所有元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找从数组B的所有元素中减去数组A的所有元素的最快方法.我知道怎么做的唯一方法是:

I am looking for the quickest method to subtract all elements of array A, from all elements of array B. The only way I know how to do it is:

a = np.array([1,2,3])
b = np.array([1,2,3])
new = []
for i in a:
    new.append(b - a[i])

理想情况下,我想得出一个等于[0,1,2;-1,0,1;-2,-1,0]

Ideally, I would like to end up with a matrix new which would be qual to [0,1,2;-1,0,1;-2,-1,0]

我还想将这种类型的操作扩展到Pandas timedelta系列.例如,我可以这样做:

I would also like to extend this type of operation to Pandas timedelta series. For example, I can do this:

a=np.array([1,2,3])
b=np.array([1,2,3])
aT = pd.to_timedelta(a,'D')
bT = pd.to_timedelta(b,'D')
new = []

for i in aT:
    x.append(bT - i)

最后得到这个:

[TimedeltaIndex(['0 days', '1 days', '2 days'], dtype='timedelta64[ns]', freq='D'), TimedeltaIndex(['-1 days', '0 days', '1 days'], dtype='timedelta64[ns]', freq='D'), TimedeltaIndex(['-2 days', '-1 days', '0 days'], dtype='timedelta64[ns]', freq='D')]

但这对于非常大的阵列来说非常慢.

but that's very slow for very large arrays. ​

推荐答案

b扩展为具有

Extend b to a 2D array case with np.newaxis/None and then let broadcasting play its part for a fast vectorized solution, like so -

a - b[:,None]

样品运行-

In [19]: a
Out[19]: array([1, 2, 3])

In [20]: b
Out[20]: array([1, 2, 3])

In [21]: a - b[:,None]
Out[21]: 
array([[ 0,  1,  2],
       [-1,  0,  1],
       [-2, -1,  0]])

这篇关于从B的所有元素中减去数组A的所有元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆