Reputation: 47
I have a list of ages in an existing dataframe. I would like to put these ages into intervals/Age Groups such as (10-20), (20-30),etc. Please see excample below
I am unsure where to begin coding this as i get an "bins" errors when using all bins related code
Upvotes: 0
Views: 516
Reputation: 118
Here's what you can do:
import pandas as pd
def checkAgeRange(age):
las_dig=age%10
range_age=str.format('{0}-{1}',age-las_dig,((age-las_dig)+10))
return range_age
d={'AGE':[19,13,45,65,23,12,28]}
dataFrame= pd.DataFrame(data=d)
dataFrame['AgeGroup']=dataFrame['AGE'].apply(checkAgeRange)
print(dataFrame)
# Output: AGE AgeGroup
0 19 10-20
1 13 10-20
2 45 40-50
3 65 60-70
4 23 20-30
5 12 10-20
6 28 20-30
Some explanation of code above:
d={'AGE':[19,13,45,65,23,12,28]}
dataFrame= pd.DataFrame(data=d)
# Making a simple dataframe here
dataFrame['AgeGroup']=dataFrame['AGE'].apply(checkAgeRange)
# applying our checkAgeRange function here
def checkAgeRange(age):
las_dig=age%10
range_age=str.format('{0}-{1}',age-las_dig,((age-las_dig)+10))
return range_age
# This method extracts the las digit from age and then forms the range as a string. You can change the data-structure here according to your needs.
Hope this answers your question. Cheers!
Upvotes: 1