0

IPython's %precision magic is quite useful (doc). It automatically rounds every numerical output on your jupyter notebook.

But absolute round is not enough sometimes. I work with values at different scales, so %precision 3 will output some values as 0.234 (good), but some other values as 6501.766 (bad).

Is there an analogous magic for significant figures? I think there is not. If that is the case, how can I implement a magic command and use it? A python function implementing this logic is for example:

def round_sig(x, sig=3):
    # round to sig significant figures
    if x == 0:
        return 0

    return round(x, sig - int(math.floor(math.log10(abs(x)))) - 1)

And a second question. How can this formatting spread to pandas.DataFrames and pandas.Series? This is, output dataframes to have this formatting too?

sheriff
  • 111
  • 5
  • [Defining custom magics](https://ipython.readthedocs.io/en/stable/config/custommagics.html) can be found in the documentation. You can use Pandas's styler abilities to control the view of series and dataframes, see [here](https://stackoverflow.com/a/46370761/8508004). – Wayne Jan 03 '23 at 20:21

0 Answers0