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, 160, 33, 42, 219, 56, 253, 163, 0, 3, 0, 13, 6, 0]
我想创建一个新列,将这个 byte_array 转换为十六进制。
此解决方案有效:
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()
感谢任何帮助!
解决方案
不确定是否有矢量化解决方案;您可能只使用该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
推荐阅读
- openedx - xblock 使安装错误
- highcharts - 在Highcharts Gantt中更改点className
- docker - Elasticsearch Docker 容器因错误而崩溃:本机控制器进程已停止 - 无法启动新的本机进程
- c# - 在 node.js 中将文件转换为字节数组
- python - 如何将带有宏的头文件预处理为非宏头文件
- python-3.x - 如何在python中将变量转换为自定义类
- java - 似乎无法让我的 JavaFX 成功运行。我正在使用我班级所需的 JRE 10.0.2
- javascript - 尝试映射枚举键以生成 JSX 元素时出现打字稿错误
- bash - 不同模式的 Sed 提取物
- html - 在css中将文本覆盖在图像上?