3

Assume the below dataframe is having column "num" of 'object' type

   num
0   0x11
1   0x3
2   0x05
3   0x4
4   0x1a
5   0x1d
6   0x82

The output of "print(df.dtypes)" is as:

Output:

 num       object

How to convert this object type column to Hex?

Expected Output: The output should be the same as the above mentioned 'df'. the type of the column 'num' should be changed to HEX.

I tried the below steps but not working:

df['num'] = [str(i) for i in df['num']]
df['num'] = [int(i,16) for i in df['num']]
df['num'] = [hex(i) for i in df['num']]
SomeOne
  • 497
  • 4
  • 9

3 Answers3

2

Use df.apply:

In [391]: df['num'] = df['num'].apply(int, base=0)

In [392]: df
Out[392]: 
   num
0   17
1    3
2    5
3    4
4   26
5   29
6  130
Mayank Porwal
  • 33,470
  • 8
  • 37
  • 58
1

You can use apply:

df['num'] = df['num'].apply(lambda x: int(x, 16))

df:

    num
0   17
1   3
2   5
3   4
4   26
5   29
6   130
Pygirl
  • 12,969
  • 5
  • 30
  • 43
1

literal_eval

from ast import literal_eval

df['num'] = df.num.map(literal_eval)

df

   num
0   17
1    3
2    5
3    4
4   26
5   29
6  130
piRSquared
  • 285,575
  • 57
  • 475
  • 624