我正在尝试编写可以将数据框 (df) 和列 (col) 作为输入并在列内从编码的 HEX 转换为 ascii 的函数。
我试过 "7061756c".decode("hex") 但我不确定我是否可以在 col 列中申请整个记录,下面是我试过的代码
def hex_to_ascii(df , col):
for i in range(0,len(df['col'].values)):
string = bytearray.fromhex(df['col'].values[i]).decode()
我被困在这里,有人可以帮忙吗
请您参考如下方法:
如果我正确理解您的数据框,您似乎只需要将 df.apply() 与您函数的修改版本一起使用:
def hex_to_ascii(s):
try:
return bytearray.fromhex(s).decode()
except ValueError:
return None # or s, or some other error handling
df['col'] = ['7061756c', '6a6f686e', '72696e676f', '67656f726765', '737475', '796f6b6f']
print(df['col'].apply(hex_to_ascii))
0 paul
1 john
2 ringo
3 george
4 stu
5 yoko
Name: col, dtype: object
