1

I have 3 numeric columns say as below:

import pandas as pd
df = pd.DataFrame()
df['col1']=[123456, 123456, 123456 ]
df['col2']=[7, 65, 150]
df['col3']=[1, 35, 60]

I want to create a new column concatenating these three columns after converting each of them to Hex numbers so that col1 is converted to 5 digit Hex, col2 is converted to 3 digit Hex and col3 is converted to 2 digit Hex. I can convert each one of them to Hex applying lambda function however, I am not able to consistently have 10 characters in the new column. Any suggestion?

Sociopath
  • 13,068
  • 19
  • 47
  • 75
Manjit P.
  • 85
  • 1
  • 7
  • Have you tried converting Hex numbers to Hex strings, concatenate them and convert the result to Hex number again? –  Sep 11 '18 at 07:25
  • No, I have not tried that way. My concern was to have the fixed concatenated length. My guess is I shall have a different result than what I want in this way. Thanks BTW for the suggestion. – Manjit P. Sep 11 '18 at 17:17

1 Answers1

1

Use:

#create dictionary for columns names with lengths
d = {'col1':5, 'col2':3, 'col3':2}

#convert to format in nested list comprehension
#https://stackoverflow.com/a/12638477
L = [["{0:0{1}x}".format(x, v) for x in df[k]] for k, v in d.items()]
print (L)
[['1e240', '1e240', '1e240'], ['007', '041', '096'], ['01', '23', '3c']]

#join strings together
df['new'] = [''.join(x) for x in zip(*L)]
print (df)

     col1  col2  col3         new
0  123456     7     1  1e24000701
1  123456    65    35  1e24004123
2  123456   150    60  1e2400963c
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252