Home > Enterprise >  Python - Create new column and add in alphabet letters
Python - Create new column and add in alphabet letters

Time:11-16

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

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?

CodePudding user response:

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'}
  • Related