0

I have a pandas dataframe on the form:

 Emotion                     Text
0   0   Say , Jim , how about going for a few beers af...
1   0   You know that is tempting but is really not g...
2   0   What do you mean ? It will help us to relax .
3   0   Do you really think so ? I don't . It will ju...
4   0   I guess you are right.But what shall we do ? ...

What I want to do is convert the Emotion column based on a dictionary mapping:

EMOTIONS = {0: neutral, 1: anger, 2: disgust, 3: fear, 4: happiness}

Ali H. Kudeir
  • 756
  • 2
  • 9
  • 19

1 Answers1

2

Original answer - apply

You can create another column applying a function to your original column.

>>> emotions_dict = {0: "neutral", 1: "anger", 2: "disgust", 3: "fear", 4: "happiness"}
>>> df["emotions_str"] = df["emotions"].apply(lambda el: emotions_dict[el])
>>> df
   emotions   text emotions_str
0         0    foo      neutral
1         0    bar      neutral
2         0    baz      neutral
3         0  hello      neutral

If you want to override your numeric column, you can just replace emotions_str with emotions.

map

The same result can be achieved with map; the assignment becomes:

>>> df["emotions_str"] = df["emotions"].map(emotions_dict)

Values not found in dictionary will be converted to NaN.

crissal
  • 2,547
  • 7
  • 25