Python: how to put my Uncertainties format into a pandas df?

75 Views Asked by At

For a Physics Experiment I'm working with uncertainties and tables. I found a code on the Internet, which helps me to print my values in the format I like them. Now I'm building a tabular with Pandas Dataframe and want to use the format there. Do you now how that works?

I'll give you a code example

import numpy as np
import uncertainties
import string
from uncertainties import ufloat

#format class

class ShorthandFormatter(string.Formatter):

    def format_field(self, value, format_spec):
        if isinstance(value, uncertainties.UFloat):
            return value.format(format_spec+'S')  # Shorthand option added
        # Special formatting for other types can be added here (floats, etc.)
        else:
            # Usual formatting:
            return super(ShorthandFormatter, self).format_field(
                value, format_spec)

frmtr = ShorthandFormatter()

#expample values
oudv = np.array([0.000002952,0.000002707,0.000002404,0.000002062,0.000001611,0.000001242,0.000000813,0.000000744])
u_v = 0.015/1000000 
dv = [ufloat(i,u_v) for i in oudv]

now iIcan print my values like this

print([frmtr.format('{0:.3u}',i) for i in dv]) 

but I want to create a table so I do this:

export = pd.DataFrame(data=dv, columns=['DV'])

when I print this it works, but with the standard format. I tried to fix it in a couple ways but none of it worked

print(frmtr.format('{0:.3u}',export))

#or I try this:
 
pd.options.display.float_format = '{0:.3u}'.format

do you know how I can fix it?

1

There are 1 best solutions below

0
vallahkriese On

Ok actually ChatGP helpd me :)

The soultion is:

def format_df(x):
 return frmtr.format('{0:.3u}',x)

and than later use

export = export.applymap(format_df)

on my dataframe