Python Forum
change numerical values to categorical names - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: change numerical values to categorical names (/thread-30528.html)



change numerical values to categorical names - JoeOpdenaker - Oct-24-2020

I am trying to convert numerical data points to categorical names in output. I want it to be labelled as categorical name but I need the raw data to stay numeric for functions elsewhere in the code. I have done this in anothe language (SAS) but I'm having trouble in python. I have found some code to clean up numbers (posted below). I do not get any errrors but it also does not change the output. Note. Please advise.

cleanup_nums = {"Congruency":     {1: 'Congruent', 2:'Incongruent'},
                "CueState": {1:'No Cue', 2: 'Center Cue', 3:'Spatial Cue' }}



RE: change numerical values to categorical names - scidam - Oct-25-2020

How can we help, if there is no code except the dictionary?
If you use pandas, you can do it easily, e.g.

In [75]: import pandas as pd
    ...:
    ...: mapper = {1: 'John', 2: 'July'}
    ...:
    ...: df = pd.DataFrame({'names': [1, 2, 1, 1], 'age': [10, 20, 10, 10]})
    ...:
    ...: df.names.map( mapper)
Output:
Out[75]: 0 John 1 July 2 John 3 John Name: names, dtype: object



RE: change numerical values to categorical names - PsyPy - Nov-02-2020

(Oct-24-2020, 07:41 PM)JoeOpdenaker Wrote: I am trying to convert numerical data points to categorical names in output. I want it to be labelled as categorical name but I need the raw data to stay numeric for functions elsewhere in the code. I have done this in anothe language (SAS) but I'm having trouble in python. I have found some code to clean up numbers (posted below). I do not get any errrors but it also does not change the output. Note. Please advise.

cleanup_nums = {"Congruency":     {1: 'Congruent', 2:'Incongruent'},
                "CueState": {1:'No Cue', 2: 'Center Cue', 3:'Spatial Cue' }}

I am not sure I understand your problem? Can you elaborate?


RE: change numerical values to categorical names - DeaD_EyE - Nov-02-2020

Example without pandas.

cleanup_nums = {
    "Congruency": {
        1: 'Congruent', 2:'Incongruent',
    },
    "CueState": {
        1:'No Cue', 2: 'Center Cue', 3:'Spatial Cue',
    },
}


# (Congruency, CueState)
data = [
    (1,2),
    (2,1),
    (1,3),
    (1,1),
]


data_categories = []
for congruency, cuestate in data:
    congruency_name = cleanup_nums["Congruency"][congruency]
    cuestate_name = cleanup_nums["CueState"][cuestate]
    row = (congruency_name, cuestate_name)
    data_categories.append(row)

print(data_categories)