简体   繁体   中英

Subtraction of different sizes numpy arrays

I have asked a previous question, but I think my example was not clear. I am still trying to subtract two different sizes of numpy arrays from a list of numpy arrays. For example:

####Data####
### For same size numpy arrays the subtraction works fine!!!!###
easy_data= [[1,2,3],[2,2,2]],[[1,2,3],[1,2,5]]
d = [np.array(i) for i in easy_data] # List of numpy arrays
res = d[1] - d[0] 
>> array([[ 0,  0,  0],
          [-1,  0,  3]])

##### Current Issue ####
data = [[1,2,3],[2,2,2]],[[1,2,3],[1,2,5],[1,1,1]]
d = [np.array(i) for i in data]
res = d[1] - d[0] #### As the sizes are different I can't subtract them ###

Desired Output

array([[ 0,  0,  0],
       [-1,  0,  3],[1,1,1])

I am kind of slow getting how to work with numpy arrays but I can't figure out how to make this work? Can anybody help me?

It's easiest to operate on a slice. If you do not want to erase the original array, use a copy:

>>> res=d[1].copy()
>>> res[:d[0].shape[0]]-=d[0]
>>> res
array([[ 0,  0,  0],
       [-1,  0,  3],
       [ 1,  1,  1]])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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