简体   繁体   中英

Use list of lists to average rows in numpy array

I want to use information from entries in a (python) list of lists to average rows of a numpy array. For example, consider the following:

LoL = [[], [0, 1, 2, 4], [3, 5], [], [6]]  #List of lists
arr = np.array([[0, 0, 0, 0], [1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3], [4, 4, 4, 4], [5, 5, 5, 5], [6, 6, 6, 6]])  #Numpy array
print arr

[[0 0 0 0]
 [1 1 1 1]
 [2 2 2 2]
 [3 3 3 3]
 [4 4 4 4]
 [5 5 5 5]
 [6 6 6 6]]

For the above list of lists ( LoL ) and numpy array ( arr ), I would like rows [0, 1, 2, 4] of arr to get averaged, rows [3, 5] of arr to get averaged between themselves and row [6] to stay in its original form. The transformed array ( arr_new ) should look like the following:

arr_new = np.array([[1.75, 1.75, 1.75, 1.75], [4.0, 4.0, 4.0, 4.0] , [6.0, 6.0, 6.0, 6.0]])
print arr_new

[[1.75 1.75 1.75 1.75]
 [4.   4.   4.   4.  ]
 [6.   6.   6.   6.  ]]

What is the most elegant way to do this?

Due to the inconsistent shape in your list of list 's, there isn't an elegant way to perform a single operation, however looping is an option and should still be efficient, since it only scales with the size of LoL :


np.stack([np.mean(arr[el], 0) for el in LoL if el])

array([[1.75, 1.75, 1.75, 1.75],
       [4.  , 4.  , 4.  , 4.  ],
       [6.  , 6.  , 6.  , 6.  ]])

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