Issue
I have this python dictionary:
dictionary = {
'1':'A',
'2':'B',
'3':'C',
'4':'D',
'5':'E',
'6':'F',
'7':'G',
'8':'H',
'8':'I',
'9':'J',
'0':'L'
}
The I have created this simple pandas dataframe:
import pandas as pd
ds = {'col1' : [12345,67890], 'col2' : [12364,78910]}
df = pd.DataFrame(data=ds)
print(df)
Which looks like this:
col1 col2
0 12345 12364
1 67890 78910
I would like to transform each and every digit in col1
(which is an int
field) to the correspondent letter as per dictionary indicated above. So, basically I'd like the resulting dataframe to look like this:
col1 col2 col1_transformed
0 12345 12364 ABCDE
1 67890 78910 FGHIJ
Is there a quick, pythonic way to do so by any chance?
Solution
A possible solution (notice that 8
is repeated in your dictionary -- a typo? -- and, therefore, my result does not match yours):
def f(x):
return ''.join([dictionary[y] for y in str(x)])
df['col3'] = df['col1'].map(f)
Output:
col1 col2 col3
0 12345 12364 ABCDE
1 67890 78910 FGIJL
Answered By - PaulS
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.