【问题标题】:Python Pandas String -> Hexadecimal -> Integer -> String ConversionsPython Pandas 字符串 -> 十六进制 -> 整数 -> 字符串转换
【发布时间】: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 的整数,最后用="" 包裹LongHexShortHex 列,这样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


    【解决方案1】:

    改变这个:

    df['LongHex'] = df['B'].apply(lambda x: hex)
    df['ShortDec'] = df['ShortHex'].apply(lambda x: int)
    

    到这里:

    df['LongHex'] = df['B'].apply(lambda x: hex(x))
    df['ShortDec'] = df['ShortHex'].apply(lambda x: int(x))
    

    另外作为旁注,我看到您稍后将它们转换为字符串,为什么不一次性完成所有操作:

    df['LongHex'] = df['B'].apply(lambda x: str(hex(x))[-4:])
    

    【讨论】:

      猜你喜欢
      • 2017-10-09
      • 2017-08-12
      • 1970-01-01
      • 2017-07-30
      • 1970-01-01
      • 2015-11-29
      • 2021-03-05
      • 2014-12-15
      相关资源
      最近更新 更多