简体   繁体   中英

Python Pandas Subset Hex String, Convert to Decimal

I've got a dataframe. Column B contains 4-character hexidecimal values:

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.

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:

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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