Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Average similar values in list and create new list with averaged values

Tags:

python

list

I have lists with many numbers which can include decimals. For example,

A = ['1', '1.01', '1.1', '2', '3', '3.2', '4', '5']

Let's say I want to get an average of those terms which differ by less than 0.5, and make a new list with those averaged terms, plus the ones which were unaffected.

In my example, the numbers 1, 1.01 and 1.1 differ by less than 0.5 to each other, so the new list would include the average of them, 1,04. Similarly, for 3 and 3.2, the new list would include the average 3,1.

So the final output would be:

B = [1.04, 2, 3.1, 4, 5]

There are some special cases, such as the list

C = [1.1, 1.2, 1.3, 1.4, 1.5, 1.6]

where certain questions arise: do we average the first 5 elements, or the last 5? If it is possible, I prefer a priority from left to right, that is, group the first 5 elements and keep the sixth one. However, it is very unlikely that the data in my lists will show such behavior, because the similar values are sufficiently close to each other. It is not really necessary to include these cases in the code, unless it is a must for it to work properly.

What is the most efficient way to do this? In practice, I'm going to use this to construct the lightcurves for different supernovae. If the difference in time between two observations is less than certain value, I may aswell consider it as a single observation made on an average time between both.

I am fairly new to Python, and all my efforts to solve this problem have failed so far... my apologies if this is too basic.

Thanks in advance!

like image 921
Kike Avatar asked Mar 18 '26 04:03

Kike


1 Answers

A = [1, 1.01, 1.1, 2, 3, 3.2, 4, 5]
groups, current_group, first = [], [], A[0]
for item in A:
    # Check if this element falls under the current group
    if item - first <= 0.5:
        current_group.append(item)
    else:
        # If it doesn't, create a new group and add old to the result
        groups.append(current_group[:])
        current_group, first = [item], item
# Add the last group which was being gathered to the result
groups.append(current_group[:])

Now, its fairly straightforward to get the average, like this

print[sum(item) / len(item) for item in groups]
# [1.0366666666666666, 2, 3.1, 4, 5]
like image 133
thefourtheye Avatar answered Mar 20 '26 16:03

thefourtheye



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!