Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 384
OnlyDean Avatar asked May 26 '26 06:05

OnlyDean


2 Answers

Just a stylistic difference, but instead of using a lambda you could also pass the keyword argument base for int() directly to apply.

df['B'] = df['B'].str[:2].apply(int, base=16)
like image 117
miradulo Avatar answered May 30 '26 09:05

miradulo


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
like image 38
EdChum Avatar answered May 30 '26 08:05

EdChum



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!