user2977664
user2977664

Reputation: 97

Python: Convert Column of letters into number

I read in a csv file into a pandas dataframe and have something like this:

  A B C D ...Z
1 5 P 8 H ...1
2 5 K 8 K ...2
3 6 K 8 K ...5

How do I convert Column B and Column D (and any other columns in dataframe) into a number? It could be A =1, B =2, etc OR I tried ord() function but it would not accept the entire Series.

Upvotes: 0

Views: 7985

Answers (2)

YOBA
YOBA

Reputation: 2807

  1. You can use this for column A for example:

    dataframe.A = [ ord(x) for x in dataframe.A ]

  2. If you want A to be 1, B to be 2 etc...

    dataframe.A = [ ord(x) - 64 for x in dataframe.A ]

Upvotes: 6

Assem
Assem

Reputation: 12077

Do something like:

for line in lines:
   new_line = map(lambda x: ord(x) - 64 if x.isalpha() else x, line)

Go through the matrix line by line, than apply in each element ord()- 65 if it is an alphabet else use it as it is. 64 is ord("A")-1.

Upvotes: 1

Related Questions