【问题标题】:How to convert hex to int in multiple pandas columns如何在多个熊猫列中将十六进制转换为整数
【发布时间】:2020-04-10 16:19:10
【问题描述】:

我正在尝试将具有十六进制值的熊猫表转换为十进制。我目前正在使用以下内容一次做一列:

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)

无论如何要一口气完成这一切?类似于:

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

我试过了:

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

但这也不起作用。

样本数据:

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

【问题讨论】:

  • 也许df[['a','b','c','d']] = df[['a','b','c','d']].applymap(int, base=16) ?
  • 等一下我现在试试
  • 你能展示一些示例数据吗?
  • applymap() 得到了一个意外的关键字参数 'base
  • 我会在一秒钟内添加它

标签: python pandas hex


【解决方案1】:

这是一个示例数据框:

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

现在,您只需要applymap

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

结果如预期:

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

【讨论】:

  • 返回 TypeError: int() can't convert non-string with explicit base,但一次只做一个是可行的......
  • @KALEB 你确定所有这些列都有string类型的对象吗?
  • 我原本以为同样的问题,但后来在每个单独的列上运行 apply 方法就像一个魅力,甚至尝试了 lambda x: int(str(x),base=16) 并没有工作
  • 我在 csv 中添加了一些示例数据
  • @KALEB 编辑了我的答案。我希望它现在有所帮助。
猜你喜欢
  • 2010-10-16
  • 2019-04-14
  • 2014-04-16
  • 2016-12-04
  • 1970-01-01
  • 2013-04-04
相关资源
最近更新 更多