【发布时间】:2017-08-06 12:42:05
【问题描述】:
我有来自嵌入式硬件的数据。消息以长十六进制的形式出现,但这个十六进制实际上是硬件将几个不同的数据组连接在 4 字符块中。为了混淆这个问题,数据库正在将这个长十六进制转换为十进制,位于我可以访问的下一层。
我的数据框:
dict = {'A': ['foo', 'bar', 'baz'], 'B': ['1346', '9953', '5246']}
df = pd.DataFrame(dict)
我想将B 列转换为一个十六进制的LongHex,将LongHex 的最后4 个字符拆分为ShortHex,将ShortHex 转换回一个名为ShortDec 的整数,最后用="" 包裹LongHex 和ShortHex 列,这样Excel 就不会将某些十六进制值转换为科学记数法。
这是我迄今为止尝试过的:
df['LongHex'] = df['B'].apply(lambda x: hex)
df['ShortHex'] = df['LongHex'].str[-4:]
df['ShortDec'] = df['ShortHex'].apply(lambda x: int)
df['LongHex'] = df['LongHex'].apply(str)
df['ShortHex'] = df['ShortHex'].apply(str)
df['LongHex'] = df['LongHex'].apply(lambda x: '="' + x + '"')
df['ShortHex'] = df['ShortHex'].apply(lambda x: '="' + x + '"')
最终这个数据帧被输出到 .csv。当我打开文件时,这是我得到的:
foo, 1346, <built-in function hex>, nan, <type 'int'>
bar, 9953, <built-in function hex>, nan, <type 'int'>
baz, 5246, <built-in function hex>, nan, <type 'int'>
【问题讨论】:
标签: python string pandas hex decimal