Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python – Create new column and add in alphabet letters

I have a dataframe and want to create a new column where each row is a letter in the alphabet and convert this into a dictionary. I am struggling with the first part.

Current dataframe:

col1 
data1
data2
data3

Desired output

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

col1  | col2
data1 | A
data2 | B 
data3 | C

Code I have tried so far:

letter ='A'
df['newcolumn'] = key_name
for index, row in df.iterrows():
    letter = chr(ord(letter) + 1)
    df['newcolumn'] = letter

The above is only giving me one value (‘B’ for all the rows). I think I am doing something incorrect in terms of the iteration – can someone please point me in the right direction?

>Solution :

Is this what you want?

from string import ascii_uppercase as ABC 
d = dict(zip(ABC[:len(df)], df.col1))    # [:len(df)] is optional. zip(ABC, df.col1) works as well

Outputs:

>>> df 

    col1
0  data1
1  data2
2  data3

>>> ABC 
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

>>> d
{'A': 'data1', 'B': 'data2', 'C': 'data3'}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading