Naravut Suvannang Naravut Suvannang - 6 months ago 12
Python Question

How can i group data based on range of values

I have data like

[312.281,
370.401,
254.245,
272.256,
312.325,
286.243,
271.231, ...]


then I want to group them by the range of value by

for i in data:
if i in range(200,300):
data_200_300.append(i)
elif i in range(300,400):
data_300_400.append(i)


it not working, what code should i use?

AKS AKS
Answer

range returns a list of integers between two numbers while your data contains floating point numbers. You can directly use Comparisons using > and < for this:

for i in data:
    if 200 < i < 300:
        data_200_300.append(i)
    elif 300 < i < 400:
        data_300_400.append(i)

If you want some matches to be inclusive, you can use <= as well.