Search code examples
pythonpandasnumericcategorical-datacontinuous

Connvert Continuous data to categorical data in Pandas dataframe


All,

I have below dataset and I Would like to add one extra column to my dataframe, that will represent/reflect the outcome in categorical data as below.

Current Dataset :enter image description here

After adding new column: enter image description here

Please advise on how to approach this.I'm new to pyton if you can provide the explanation, that will be great!


Solution

  • You can using map after create the dict , but let us try something new

    pd.cut(df.Seasons,4,labels=['Winter','Spring','Summer','Fall'])
    Out[262]: 
    0    Winter
    1    Spring
    2    Summer
    3      Fall
    4    Summer
    dtype: category
    Categories (4, object): [Winter < Spring < Summer < Fall]
    

    Ok Using map

    d=dict(zip([1,2,3,4],['Winter', 'Spring', 'Summer', 'Fall']))
    df.Seasons.map(d)
    Out[265]: 
    0    Winter
    1    Spring
    2    Summer
    3      Fall
    4    Summer
    dtype: object