【问题标题】:pandas string column of base64 to hexbase64的熊猫字符串列到十六进制
【发布时间】:2018-12-03 04:13:20
【问题描述】:

所以,我有一个被归类为“对象”的 pandas 数据帧,但实际上是 base64 编码的有效负载,我想将其转换为十六进制。

raw
AIgIm/H/SfwAR2IBAgMgAgIAAQMCAFoAcQAAAAAAAAFxAAAAAAAAA4gAAABiAF8AABI=
AIgIm/v/SfsAUNwBAgMgAgIAEgMCAEIAcQAAAAAAAAFxAAAAAAAAA4gAAABkAF8AAAw=
AIgIm/z/Sg4AVroBAgMgAgIA6wMCAFgAcQAAAAAAAAFxAAAAAAAAA4geAAFEADoAGQs=

使用https://cryptii.com/base64-to-hex 我得到这些值(这是我所期望的):

new_raw
00 88 08 9b f1 ff 49 fc 00 47 62 01 02 03 20 02 02 00 01 03 02 00 5a 00 71 00 00 00 00 00 00 01 71 00 00 00 00 00 00 03 88 00 00 00 62 00 5f 00 00 12
00 88 08 9b fb ff 49 fb 00 50 dc 01 02 03 20 02 02 00 12 03 02 00 42 00 71 00 00 00 00 00 00 01 71 00 00 00 00 00 00 03 88 00 00 00 64 00 5f 00 00 0c
00 88 08 9b fc ff 4a 0e 00 56 ba 01 02 03 20 02 02 00 eb 03 02 00 58 00 71 00 00 00 00 00 00 01 71 00 00 00 00 00 00 03 88 1e 00 01 44 00 3a 00 19 0b

根据之前提出的类似问题,我已经尝试过:

df['new_raw'] = df['raw'].apply(lambda x: x.decode("base64").encode("hex"))

但这给了我:

AttributeError: 'str' object has no attribute 'decode'` error.

【问题讨论】:

    标签: python pandas base64 hex


    【解决方案1】:

    您有 Python 3 字符串对象,它们没有 .decode() 方法。解码是您对字节值执行的操作以获取字符串,您将 编码 的字符串。您似乎找到了一些 Python 2 特定的代码来进行不兼容的转换。

    要将 Base64 数据转换为二进制,然后再转换为十六进制,请使用 base64 module,然后调用 .hex() 方法:

    import base64
    
    df['raw'].apply(lambda b: base64.b64decode(b).hex())
    

    演示:

    >>> import pandas as pd
    >>> import base64
    >>> df = pd.DataFrame({'raw': '''\
    ... AIgIm/H/SfwAR2IBAgMgAgIAAQMCAFoAcQAAAAAAAAFxAAAAAAAAA4gAAABiAF8AABI=
    ... AIgIm/v/SfsAUNwBAgMgAgIAEgMCAEIAcQAAAAAAAAFxAAAAAAAAA4gAAABkAF8AAAw=
    ... AIgIm/z/Sg4AVroBAgMgAgIA6wMCAFgAcQAAAAAAAAFxAAAAAAAAA4geAAFEADoAGQs=
    ... '''}, index=[0, 1, 2])
    >>> df['raw'].apply(lambda b: base64.b64decode(b).hex())
    0    0088089bf1ff49fc00476201020320020200010302005a...
    1    0088089bf1ff49fc00476201020320020200010302005a...
    2    0088089bf1ff49fc00476201020320020200010302005a...
    Name: raw, dtype: object
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-10-04
      • 2014-03-07
      • 1970-01-01
      • 2018-03-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多