Reputation: 23811
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])
Upvotes: 3
Views: 1583
Reputation: 879361
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
Upvotes: 2
Reputation:
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 :)
Upvotes: 3
Reputation: 2046
You would want to clusterize these elements, probably with the k-mean algorithm, here are some answers: Python k-means algorithm
Upvotes: 0