我想将x列中的十六进制转换为正确的负整数,如“true”列所示,但在y列中得到了结果。

x        y     true
fdf1   65009   -527

我试过这个(我知道不对)
df["y"] = df["x"].apply(int,base=16)

从这里我知道这个函数:
def s16(value):
    return -(value & 0x8000) | (value & 0x7fff)

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

可以将单个值转换为正确的值,但如何应用它在Pandas数据框中创建新列?

最佳答案

使用lambda功能:

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

或更改cleaner代码的函数:
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

10-07 13:38
查看更多