Home > Net >  I try to map values to a column in pandas but i get nan values instead
I try to map values to a column in pandas but i get nan values instead

Time:11-30

This is my code:

mapping = {"ISTJ":1, "ISTP":2, "ISFJ":3, "ISFP":4, "INFP":6, "INTJ":7, "INTP":8, "ESTP":9, "ESTJ":10, "ESFP":11, "ESFJ":12, "ENFP":13, "ENFJ":14, "ENTP":15, "ENTJ":16, "NaN": 17}
q20 = castaway_details["personality_type"]
q20["personality_type"] = q20["personality_type"].map(mapping)

the data frame is like this

   personality_type  
0   INTP     
1   INFP     
2   INTJ    
3   ISTJ     
4   NAN   
5   ESFP    

I want the output like this:

   personality_type  
0   8     
1   6     
2   7    
3   1     
4   17   
5   11

however, what I get from my code is all NANs

CodePudding user response:

Try to pandas.Series.str.strip before the pandas.Series.map :

q20["personality_type"]= q20["personality_type"].str.strip().map(mapping)

# Output :

print(q20)

   personality_type
0                 8
1                 6
2                 7
3                 1
4                17
5                11

CodePudding user response:

The key NaN in your mapping dictionary and NaN value in your data frame do not match. I have modified the one in your dictionary.

df.apply(lambda x: x.fillna('NAN').map(mapping))

   personality_type
0                 8
1                 6
2                 7
3                 1
4                17
5                11
  • Related