Search code examples
pythonpandasnumericcategorical-datacontinuous

How to convert continous data to Categorical in python?


All,

My dataset looks like following, and I Would like to add one column which can convert my last column i.e Day_of_The_week to Mon, Tue, Wed. Note: Day_of_the_week include 5 days : Mon,Tue,Wed,Thurs,Fri. I checked link but couldn't figure out how to implement in my dataframe

enter image description here

I would like to convert my pandas dataframe as below: enter image description here

Being a newbie to python,if you could provide explanation, that will be great!


Solution

  • calendar.day_name + pd.Series.map

    You can construct a dictionary and then map your integer series to a list of day strings:

    import pandas as pd
    from calendar import day_name
    from collections import deque
    
    df = pd.DataFrame({'Day_of_the_week': [2, 3, 4, 4, 5, 6, 6]})
    
    days = deque(day_name)
    days.rotate(df['Day_of_the_week'].iat[0])  # rotate days
    days_map = dict(enumerate(days))           # construct dictionary
    
    df['Day_Factor'] = df['Day_of_the_week'].map(days_map)
    
    print(df)
    
       Day_of_the_week Day_Factor
    0                2     Monday
    1                3    Tuesday
    2                4  Wednesday
    3                4  Wednesday
    4                5   Thursday
    5                6     Friday
    6                6     Friday