2

I want to convert hex in column x into correct negative int as seen in column "true", but instead i got result in column y.

x        y     true
fdf1   65009   -527

I tried this (I know it's not correct)

df["y"] = df["x"].apply(int,base=16)

and from this link I know this function:

def s16(value):
    return -(value & 0x8000) | (value & 0x7fff)

a = s16(int('fdf1', 16))
print(a)

can convert single value into correct one but how do you apply it to make a new column in Pandas data frame?

npm
  • 643
  • 5
  • 17

2 Answers2

3

Use lambda function:

df["y"] = df["x"].apply(lambda x: s16(int(x, base=16)))

Or change function for cleaner code:

def s16(value):
    value = int(value, base=16)
    return -(value & 0x8000) | (value & 0x7fff)

df["y"] = df["x"].apply(s16)
print (df)
      x    y  true
0  fdf1 -527  -527
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
2

The easiest way is to convert it to an integer and reinterpret it as a 16-bit integer by using .astype:

import numpy as np
df["y"] = df["x"].apply(lambda x: int(x, base=16)).astype(np.int16)

The dtype of column y will be int16, so any operation done on this column with other int16's will keep the values between -32768 and 32767.

Rob
  • 3,418
  • 1
  • 19
  • 27