Skip to content

Instantly share code, notes, and snippets.

@pmav99
Created October 15, 2016 09:36
Show Gist options
  • Save pmav99/884b6584b13d85094f87d91b68b7458a to your computer and use it in GitHub Desktop.
Save pmav99/884b6584b13d85094f87d91b68b7458a to your computer and use it in GitHub Desktop.
Python Float formatting
# first cell
import os
import glob
import locale
import numpy as np
import pandas as pd
from IPython.core.interactiveshell import InteractiveShell
# Set jupyter/pandas options
InteractiveShell.ast_node_interactivity = "all"
pd.set_option('display.max_columns', None)
pd.set_option('display.max_rows', None)
# set float formatting
locale.setlocale(locale.LC_ALL, '')
locale._override_localeconv = {'mon_thousands_sep': '_'} # you can change the "_" with any character you want.
float_formatter = lambda x: locale.format('%.2f', x, grouping=True, monetary=True)
pd.set_option("display.float_format", float_formatter)
np.set_printoptions(formatter={'float': float_formatter})
# 2nd cell
number = 1234567890123.1234
# the default output format cannot change
number
# but we can always use our own formatter
float_formatter(number)
# numpy and pandas also respect the options we've set.
my_array = np.array([1, 3.3, number])
my_array
pd.DataFrame(my_array)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment