I would like to append a letter (in an alphabetical order)to my dataframe starting from a specific letter which I have stored in a variable.
Current dataframe:
col1
data1
data2
data3
Variable to assign (could be any letter of the alphabet)
variable ='D'
Desired output as dataframe
col1 | col2
data1 | E
data2 | F
data3 | G
I can assign ABCDE etc using the code below. For my case I have to assign it from a specific letter (e.g if letter B
then next should be C
etc
from string import ascii_uppercase as ABC
d = dict(zip(ABC[:len(df)], df.col1))
Desired output as dictionary
output = {'E': 'data1', 'F': 'data2', 'G': 'data3'}
Could someone guide me on the above?
CodePudding user response:
Use ord
to create start point for ascii code
start_ascii = ord(variable) 1
Map using chr
to the generated ord
values
df['col2'] = list(map(chr, range(start_ascii, start_ascii df.shape[0])))
Dataframe becomes
col1 col2
0 data1 E
1 data2 F
2 data3 G
Convert to dictionary
dict(zip(df.col2, df.col1))
Output
{'E': 'data1', 'F': 'data2', 'G': 'data3'}
CodePudding user response:
You can make use of the RangeIndex
:
df["new"] = (df.index ord(variable) 1).map(chr)
print (df.set_index("new")["col1"].to_dict())
{'E': 'data1', 'F': 'data2', 'G': 'data3'}