KALEB
KALEB

Reputation: 65

How to convert hex to int in multiple pandas columns

I am trying to convert a pandas table that has hex values to decimal. I am currently I am doing this one column at a time with the below:

df["a"] = df["a"].apply(int,base=16)
df["b"] = df["b"].apply(int,base=16)
df["c"] = df["c"].apply(int,base=16)
df["d"] = df["d"].apply(int,base=16)

Anyway to do this all in one go? similar to:

df[['a','b','c','d']] = df[['a','b','c','d']].apply(int,base=16,axis=1)

I tried:

df[['a','b','c','d']] = df[['a','b','c','d']].apply(lambda x: int(x,base=16),axis=1)

but this did not work as well.

Sample Data:

      A                    B        C
0  0x26  0x526aada8ffd9e0000  0x15f90
1  0x26                  0x0  0x222e0
2  0x25                  0x0  0x222e0

Upvotes: 0

Views: 885

Answers (1)

Giorgos Myrianthous
Giorgos Myrianthous

Reputation: 39880

So here's a sample dataframe:

>>> df
      A                    B        C
0  0x26  0x526aada8ffd9e0000  0x15f90
1  0x26                  0x0  0x222e0
2  0x25                  0x0  0x222e0

Now, all you need is applymap:

>>> hex_to_int = lambda x: int(x, 16)
>>> df[['A', 'B', 'C']] = df[['A', 'B', 'C']].applymap(hex_to_int)

And the result is as expected:

>>> df
    A                     B       C
0  38  95020000000000000000   90000
1  38                     0  140000
2  37                     0  140000

Upvotes: 1

Related Questions