Home > Back-end >  Faster way of adding results of computed medians to list without for cycle?
Faster way of adding results of computed medians to list without for cycle?

Time:11-29

I would be interested in another, faster, way of adding the median values ​​to the sheet without using a for loop.

Suppose I have the following matrix:

data_matrix = [
[2,4,5,6,4]
[5,6,5,6,4]
.
.
.
[etc.,..,etc.]
]

I want to calculate the median from each row and insert the results into a 1D list medians[]. The list median[] will therefore contain the calculated values ​​of the medians.

I did it with for cycle and it works without problem:


medians = []

for data_row in data_matrix:
    medians.append(median(delta_row))

Ok, it works fine but I´m not sure if this method isn´t slow for more computations.

Is anoter way which does the same as code above but speed of code would be faster?

CodePudding user response:

If you don't want to loop (python loop), use :

import numpy as np

data_matrix = [
[2,4,5,6,4],
[5,6,5,6,4],
]

out = np.median(data_matrix, axis=1).tolist()

Output: [4.0, 5.0]

  • Related