编写一个可以在熊猫数据框中从十六进制转换为ASCII格式的函数

Mav*_*ick 1 python pandas

我正在尝试编写可以将数据帧(df)和column(col)作为输入并将column中的编码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()
Run Code Online (Sandbox Code Playgroud)

我被困在这里,有人可以帮忙吗

Ran*_*ndy 5

看来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
Run Code Online (Sandbox Code Playgroud)