简体   繁体   中英

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

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM