代码之家  ›  专栏  ›  技术社区  ›  Kvothe

PANDAS字节数组到十六进制转换

  •  0
  • Kvothe  · 技术社区  · 7 年前

    byte_array
    [0, 136, 7, 224, 13, 255, 250, 36, 0, 25, 131, 1, 2, 1, 144, 2, 2, 2, 7, 3, 2, 5, 142, 0, 113, 252, 34, 70, 39, 43, 241, 1, 113, 0, 0, 0, 0, 0, 0, 2, 113, 255, 255, 248, 248, 0, 0]
    [56, 79, 250, 88, 185, 29, 25, 231, 160, 33, 42, 219, 56, 253, 163, 0, 3, 0, 13, 6, 0]
    

    test_array = [0, 136, 7, 224, 13, 255, 250, 36, 0, 25, 131, 1, 2, 1, 144, 2, 2, 2, 7, 3, 2, 5, 142, 0, 113, 252, 34, 70, 39, 43, 241, 1, 113, 0, 0, 0, 0, 0, 0, 2, 113, 255, 255, 248, 248, 0, 0]

    print(bytes(test_array).hex())

    预期输出: 008807e00dfffa2400198301020190020202070302058e0071fc2246272bf101710000000000000271fffff8f80000

    df['hex_column'] = bytes(df['byte_array']).hex()

    1 回复  |  直到 7 年前
        1
  •  2
  •   akuiper    7 年前

    apply 方法,并逐元素转换序列元素:

    df['hex_column'] = df['byte_array'].apply(lambda x: bytes(x).hex())
    

    df = pd.DataFrame({'byte_array': [[1,4,136], [2, 255, 3]]})
    
    df
    #    byte_array
    #0  [1, 4, 136]
    #1  [2, 255, 3]
    
    df['hex_column'] = df['byte_array'].apply(lambda x: bytes(x).hex())
    
    df
    #    byte_array hex_column
    #0  [1, 4, 136]     010488
    #1  [2, 255, 3]     02ff03