Home > Software engineering >  Convert letter into numeric value
Convert letter into numeric value

Time:03-24

I have column in Pandas dataframe which has values from A-Z. I want to replace the letter value into numeric value. i.e A = 1, B = 2 etc

I tried below and it works but is there an efficient way to replace the value to numeric?

key = {'A': 1, 'B': 2, 'C': 3, 'D': 4, 'E': 5, 'F': 6, 'G': 7, 'H': 8, 'I': 9,
       'J': 10, 'K': 11, 'L': 12, 'M': 13, 'N': 14, 'O': 15, 'P': 16, 'Q': 17,
       'R': 18, 'S': 19, 'T': 20, 'U': 21, 'V': 22, 'W': 23, 'X': 24, 'Y': 25,
       'Z': 26}

df.replace({'letter_column': key})

CodePudding user response:

You can use dict comprehension:

df = df.replace({'letter_column': {chr(i   64): i for i in range(1, 27)}})

CodePudding user response:

you can use ord() which maps ASCII characters:

df = pd.DataFrame(['A','B','C'], columns = ['letter'])

df['letter'].apply(lambda x:ord(x)-64)

CodePudding user response:

You can do

df[:] = df.to_numpy().astype('<U1').view(np.uint32)-64
  • Related