简体   繁体   English

Python Pandas子集十六进制字符串,转换为十进制

[英]Python Pandas Subset Hex String, Convert to Decimal

I've got a dataframe. 我有一个数据帧。 Column B contains 4-character hexidecimal values: B列包含4个字符的十六进制值:

dict = {'A': ['foo', 'bar', 'baz'], 'B': ['1346', '0f46', '5a46']}
df = pd.DataFrame(dict)

I am only interested in the first two characters of the hex in Column B. I want to replace Column B with the only the first two characters in the hex, and then convert them to decimal. 我只对列B中十六进制的前两个字符感兴趣。我想用十六进制中只有前两个字符替换B列,然后将它们转换为十进制。

So the end result should be a data frame that looks like this: 所以最终结果应该是一个如下所示的数据框:

A    B
foo  19
bar  15
baz  90

I can't even figure how to get the first two characters sub-setted. 我甚至无法弄清楚如何获得前两个字符的子设置。 This seems like it should work, but it doesn't: 这似乎应该有效,但它没有:

df.B.str[:2]

Any help would be greatly appreciated. 任何帮助将不胜感激。

You can slice the column using str[:2] and then call apply and use a lambda to convert the hex to decimal: 您可以使用str[:2]对列进行切片,然后调用apply并使用lambda将十六进制转换为十进制:

In [255]:    
df['B'] = df['B'].str[:2].apply(lambda x: int(x,16))
df

Out[255]:
     A   B
0  foo  19
1  bar  15
2  baz  90

只是风格差异,但是你也可以直接将int()的关键字参数base传递给apply ,而不是使用lambda。

df['B'] = df['B'].str[:2].apply(int, base=16)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM