'DataFrame to_csv: float format depending on value

I used to format individual float values like this to fit them in a Word table:

if abs(v) < 0.01 or abs(v) >= 100000:
    s = format(v, '5.3e')
else:
    s = format(v, '.4g')
s = s.replace('.', ',')

Now I want to do it using converting pivot table to csv, but I don't know how to specify a float format depending on value:

s = pv.to_csv(sep='\t', decimal=',', float_format=???)

Is there a way to implement this?



Solution 1:[1]

Use applymap:

pv = pv.applymap(lambda x: '%5.3e' % x if (abs(x) < 0.01 or abs(x) >= 100000) else '%.4g' % x)
pv = pv.applymap(lambda x: x.replace('.', ','))

as per OP Michael's own prior edit to the question.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 vinzee