如何在Python中将pandas read_sql读取的bytes列转换为十六进制?
解决pandas读取SQL bytes列后的格式转换问题
直接通过自定义转换函数结合pandas.Series.apply()就能实现需求,把bytes格式转成0x开头的大写十六进制字符串:
基础实现代码
import pandas as pd # 假设你的DataFrame是df,目标列名为'guid' def convert_bytes_to_hex(b): return f"0x{b.hex().upper()}" # 对目标列应用转换 df['guid'] = df['guid'].apply(convert_bytes_to_hex)
带空值处理的版本
如果列中存在None空值,为避免报错,给函数加个空值判断:
def convert_bytes_to_hex(b): if b is None: return None return f"0x{b.hex().upper()}" df['guid'] = df['guid'].apply(convert_bytes_to_hex)
代码说明
b.hex():将bytes对象转为小写的十六进制字符串(比如b'\x80\xbc'会输出'80bc').upper():把十六进制字符串转为大写格式- 拼接
0x前缀,最终得到你需要的0x80BC10604BA895D811E54BF9E7D78C71格式
内容的提问来源于stack exchange,提问作者fikos
相关产品推荐
相关产品推荐

