Skip to content
Advertisement

Hexadecimal to ASCII string in Pandas

I have this pandas datafreme

data1_txt = """
Name
0x41
0x4a
0x47
"""
df = pd.read_fwf(io.StringIO(data1_txt))

As you can see it’s in Hex and I need to convert it to ASCII character. Hence, I need it to look like this

data1_txt = """
Name
A
J
G
"""
df = pd.read_fwf(io.StringIO(data1_txt))

I can do this in plain python, but I can’t do it in Pandas. AnĂ½ help is very much appreciated

Advertisement

Answer

Use lambda function or lsit comprehension:

df['Name'] = df['Name'].map(lambda x: chr(int(x, 16)))
#alternatives
df['Name'] = df['Name'].apply(lambda x: chr(int(x, 16)))
df['Name'] = [chr(int(x, 16)) for x in df['Name']]
print (df)
  Name
0    A
1    J
2    G

Another idea:

df['Name'] = df['Name'].map(lambda x: bytes.fromhex(x[2:]).decode('utf-8'))
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement