EN VI

Python - Display/print column as hex in pandas?

2024-03-11 18:30:04
How to Python - Display/print column as hex in pandas?

Let's say I have this data as a starting point:

import pandas as pd

data = [
  {"colA": "hello", "colB":  22, "colC": 3.0, "colD":   123476},
  {"colA": "there", "colB": 122, "colC": 4.0, "colD":  2384953},
  {"colA": "world", "colB": 222, "colC": 5.0, "colD": 39506483},
]

df = pd.DataFrame(data)

with pd.option_context('display.max_rows', None, 'display.max_columns', None, 'display.width', None, 'max_colwidth', 20, 'display.float_format', "{:.2f}".format):
  print(df)

It prints:

    colA  colB  colC      colD
0  hello    22  3.00    123476
1  there   122  4.00   2384953
2  world   222  5.00  39506483

Now, I would like ONLY the integer column B to be printed as hex - more specifically, as "0x{:02X}" string format.

If it existed, I might have used display.int_format, but that option does not exist as stated in Can you format pandas integers for display, like `pd.options.display.float_format` for floats? ... Then again, such an option would likely not allow me to print ONLY column B in that way.

Another option is doing .apply() as hinted in Converting a string of numbers to hex and back to dec pandas python:

# ...
df = pd.DataFrame(data)

df["colB"] = df["colB"].apply("0x{:02X}".format)
# ...

... which then prints what I want:

    colA  colB  colC      colD
0  hello  0x16  3.00    123476
1  there  0x7A  4.00   2384953
2  world  0xDE  5.00  39506483

... however, it also changes the data in my table - and I would like to preserve the original data in the table; I simply want to print some columns as hex.

So - is there a way to specify only some certain columns to be printed as hex in pandas, while keeping the original data in the table (and without explicitly copying the dataframe to a new one just for that kind of printing)?

Solution:

You can try to use pandas.io.formats.style.Styler:

style = df.style.format({"colB": "0x{:02X}"}, precision=2)
print(style.to_string(delimiter="\t"))

Prints:

        colA    colB    colC    colD
0       hello   0x16    3.00    123476
1       there   0x7A    4.00    2384953
2       world   0xDE    5.00    39506483
Answer

Login


Forgot Your Password?

Create Account


Lost your password? Please enter your email address. You will receive a link to create a new password.

Reset Password

Back to login