简体   繁体   中英

python - Adding combinations of adjacent rows in a matrix

This is my first post here and I'm a python beginner - all help is appreciated!

I'm trying to add all combinations of adjacent rows in a numpy matrix. ie row 1 + row 2, row 2 + row 3, row 3 + row 4, etc... with output to a list

I will then look for the smallest of these outputs and select that item in the list to be printed

I believe I need to use a for loop of some sort but I really am a novice...

Just iterate over the length of the array - 1 and add the pairs as you go into a new list. Then, select the one you want. For example:

>>> x = np.array([[1,2,3], [4,5,6], [7,8,9]])
>>> print [x[i] + x[i+1] for i in range(len(x)-1)]
 [array([5, 7, 9]), array([11, 13, 15])]

Suppose you have this

import numpy as np 
arr = np.array([[1, 2, 3],
                [4, 5, 6],
                [7 , 8, 9]])

You can first calculate the sum of each row by using np.sum(arr, axis=1) the argument axis=1 allows to sum each column entries for each line.

In this case, sums = np.sum(arr, axis=1) = array([ 6, 15, 24]) .

Then you can iterate over this tab to add the different sums :

lst_sums = []
for s in range(len(sums)-1) :
    lst_sums.append(sums[i]+sums[i+1])

Then you can sorted or getting the np.min(sums)

If you need more details you can look at numpy function docs, same for the lists

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