Bogdan Titomir
Bogdan Titomir

Reputation: 337

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

Upvotes: 1

Views: 597

Answers (1)

jezrael
jezrael

Reputation: 863226

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'))

Upvotes: 2

Related Questions