Arrays 字节数组到十六进制的转换

Arrays 字节数组到十六进制的转换,arrays,pandas,Arrays,Pandas,所以我得到了一个包含一列字节数组的数据帧 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, 1

所以我得到了一个包含一列字节数组的数据帧

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_数组=[0,136,7,224,13,255,250,36,0,25,131,1,2,1,144,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,248,0,0]

打印(字节(测试数组).hex())

预期产出:
008807E00DFFFA2400198301020190202070302058E0071FC2246272BF101710000000000000271FFF80000

然而,我似乎无法将此应用于整个熊猫数据帧。下面的代码给出了不正确的结果

df['hex\u column']=字节(df['byte\u array'])。hex()


谢谢你的帮助

不确定是否存在矢量化解决方案;您可以使用
apply
方法,逐个元素转换序列元素:

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


啊,我有一个错误:
TypeError:string参数没有编码。你知道我如何包含编码吗?你的列表可能是一个字符串。尝试先将它们转换为list
import ast
然后再转换为
lambda x:bytes(ast.literal\u eval(x)).hex()
啊,我想这是我的数据帧有问题。它有大约500k行,并抛出以下错误:
TypeError:无法将“float”对象转换为字节
但您的答案是正确的。我只需要想个办法把彩车处理掉。当我执行astype('str')
时,它抛出了前面的错误。实际上,现在我仔细查看了数据。该列实际包含
nan
!该死的,我花了很长时间才弄明白。无论如何,我会接受你的回答,因为现在一切都好了:D
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