3

I'm running a simulation in which people age in small (month, week) increments. However, I have hazards in non-consistent age-intervals. Is there an simple/efficient way to round my age at any time to the nearest age-group (for the purpose of extracting the hazards for that age?

age_groups = np.array([0, .01, .1, 5, 10, 15, 20, 25, 30, 35, 40])
Matt Ball
  • 354,903
  • 100
  • 647
  • 710
mike
  • 22,931
  • 31
  • 77
  • 100
  • 1
    Could you give an example of your hazard age intervals? It sounds like you want to just identify which hazard groups each individual fits into, but I can't quite tell from the information you've given. – Lee Netherton Aug 10 '11 at 16:07

3 Answers3

3

I assume you have ages such as .5, 5, 6, 10, 32, 32.5, ect. that need to fall into the age_groups array you have.

This is an easy one-liner :)

Assuming you have:

age_groups = np.array([0, .01, .1, 5, 10, 15, 20, 25, 30, 35, 40])
age = .5

The solution is:

nearest_age = age_groups[(np.abs(age_groups-age)).argmin()]

Put that line into a function, passing it the age_groups array and the age you want rounded :)

  • Note that this doesn't vectorize, unless you broadcast and create a big array, unutbu's answer with searchsorted is the efficient vectorized version. – Josef Aug 11 '11 at 10:52
2

Suppose you want to group the ages into bins defined by age_groups. Then you can find which age range each age falls into using np.searchsorted:

import numpy as np

ages=np.array([0,0.05,1,3,5,10,13,19,25,35])

age_groups = np.array([0, .01, .1, 5, 10, 15, 20, 25, 30, 35, 40])

index=age_groups.searchsorted(ages,side='left')
for age,nearest_age in zip(ages,age_groups[index]):
    print('{a} --> {n}'.format(a=age,n=nearest_age))

yields

0.0 --> 0.0
0.05 --> 0.1
1.0 --> 5.0
3.0 --> 5.0
5.0 --> 5.0
10.0 --> 10.0
13.0 --> 15.0
19.0 --> 20.0
25.0 --> 25.0
35.0 --> 35.0
unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
0

You would want to clusterize these elements, probably with the k-mean algorithm, here are some answers: Python k-means algorithm

Community
  • 1
  • 1
BrainStorm
  • 2,036
  • 1
  • 16
  • 23