我有3个数字列,说明如下:
import pandas as pd
df = pd.DataFrame()
df['col1']=[123456, 123456, 123456 ]
df['col2']=[7, 65, 150]
df['col3']=[1, 35, 60]
我想在将这三列转换为十六进制数字后创建一个新列,以将col1转换为5位十六进制,col2转换为3位十六进制,而col3转换为2位十六进制。我可以使用lambda函数将它们中的每一个都转换为十六进制,但是,我不能在新列中始终保持10个字符。有什么建议吗?
答案 0 :(得分:1)
使用:
#create dictionary for coolumns 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