Kvothe
Kvothe

Reputation: 1393

Pandas Hexadecimal To Text Conversion

I'm trying to convert a dataframe that contains hexadecimal values into text

foo_hex bar_hex baz_hex qux_hex foo_text bar_text baz_text qux_text
30      2D3436  2D3630  3438

Using an online converter: http://www.unit-conversion.info/texttools/hexadecimal/

foo_hex bar_hex baz_hex qux_hex foo_text bar_text baz_text qux_text
30      2D3436  2D3630  3438    0        -46      -60      48

I have a dataframe of 000's of rows, so I'm wondering if this can be done using Pandas.

I have tried:

df1['foo_text'] = df1['foo_hex'].apply(lambda x: int(x, base=16))

But the answer is not as per the conversion tool.

Appreciate any help!

Upvotes: 2

Views: 400

Answers (1)

Anand S Kumar
Anand S Kumar

Reputation: 90979

Based on the examples provided, you need to group the hexadecimal into groups of 2, and then take decimal values for each group separately and then convert them back to char (to convert them to text). Example -

def func(a):
    b = [iter(a)] * 2
    result = ''
    for char1,char2 in zip(*b):
        result = result + chr(int(char1+char2,base=16))
    return result

df1['foo_text'] = df1['foo_hex'].apply(func)

Upvotes: 2

Related Questions