Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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'))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading