Mapping alphabets to its numeric equivalent?
Please see my code below. I'm iterating through strings like '1A', '4D', etc, and I want the output to instead be 1.1, 4.4, and so on..see below.
Instead of 1A I want 1.1, 1B= 1.2, 4A = 4.1, 5D = 5.4, etc...
Convert alphabet letters to number in Python
data = ['1A','1B','4A', '5D','']
df = pd.DataFrame(data, columns = ['Score'])
newcol = []
for col, row in df['Score'].iteritems()
if pd.isnull(row):
newcol.append(row)
elif pd.notnull(row):
newcol.append(#FIRST ELEMENT OF ROW, 1-5,'.',
#NUMERIC EQUIVALENT OF ALPHA, IE, A=1, B=2, C=3, D=4, etc)
You can use str.replace
:
df['Score'] = df['Score'].str.replace('\D',
lambda x: f'.{ord(x.group(0).upper())-64}', regex=True)
output:
Score
0 1.1
1 1.2
2 4.1
3 5.4
4
Use (with @Ch3steR's comment)-
from string import ascii_uppercase
dic = {j:str(i) for i,j in enumerate(ascii_uppercase, 1)}
df['Score'].str[:-1] + '.' + df['Score'].str[-1].map(dic)
Output
0 1.1
1 1.2
2 4.1
3 5.4
4 NaN
Name: Score, dtype: object