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]) 
1
  • 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. Commented Aug 10, 2011 at 16:07

3 Answers 3

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 :)

Sign up to request clarification or add additional context in comments.

1 Comment

Note that this doesn't vectorize, unless you broadcast and create a big array, unutbu's answer with searchsorted is the efficient vectorized version.
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 

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.