Search code examples
pythonpandasmappingbinning

pandas.cut with enumerated bins


Let us say I have the following data (which is a simplified but accurate representation of my actual data):

df 
    Age   Country
0    10     1
1    15     2
2    20     3
3    25     1
4    30     2
5    15     3
6    20     3
7    15     4
8    20     4

I would like to use pandas.cut to bin countries 1 and 3 into bin1, and countries 2 and 4 into bin2. Neither binning with a preset number of bins, nor binning with edges will work. In some possible world, this would be achieved with the following code that just unfortunately happens to be ill-formed in the actual world:

conts = [‘Africa’, ‘Asia’]
bins = [[1,3], [2,4]]
df['Continent'] = pd.cut(df['Country'], bins, labels = conts)

Is there some functionality in pandas, or a simple workaround I am missing?


Solution

  • As EdChum already pointed out, map is the way to go here

    continent_lookup = {1: 'Africa', 2: 'Asia', 3: 'Africa', 4: 'Asia'}
    df['Continent'] = df.Country.map(continent_lookup)