Output data Formatting - Decimal place, Missing values

I am using pandas DataFrame in my app. I am using following code to display the data.

The output have too many decimal places and display “NaN” or “nan” if data is missing. Out put are showing below.

formatting_output

Please suggest how to resolve the following problem:

  * Customize number of decimal places
  * Remove or Replace "NaN" or "nan" if data is missing. 

Thank you in advance.

Hi @mitalee.ghy, and welcome to the community!

choosing ‘N’ decimals

You can call str.format(float) with str as "{:.xf}" to get a string representation of float with x decimal places.

value = 3.3333333333
formatted_string = "{:.2f}".format(value)
# format to two decimal places
float_value = float(formatted_string)
st.write(float_value)

choosing ‘N’ decimals right in Pandas

You can also do this directly in Pandas! :panda_face:

By providing an integer each column is rounded to the same number of decimal places, e.g.:

df.round(1)

With a dict, the number of places for specific columns can be specified with the column names as key and the number of decimal places as value, e.g.:

df.round({'dogs': 1, 'cats': 0})

NaN values

You can replace NaN values with null via df.fillna(’’, inplace=True)

I hope this solves your issue. Let us know :slight_smile:

Best,
Charly

For simplicity and I suggest the single line formatting below

st.write(’- Monthly Sales: ', df_mar2021[‘MonSales’].style.format("{:.2f}")

Note: This requires Pandas 1.2.4, there is a regression related to 1.3.0 that is not yet resolved.