SomeOne
SomeOne

Reputation: 497

Ho to convert a column of object type to HexaDecimal

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

Upvotes: 3

Views: 295

Answers (3)

piRSquared
piRSquared

Reputation: 294488

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

Upvotes: 1

Mayank Porwal
Mayank Porwal

Reputation: 34086

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

Upvotes: 2

Pygirl
Pygirl

Reputation: 13349

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

Upvotes: 1

Related Questions