Home > database >  How do round decimals when writing dataframe in streamlit
How do round decimals when writing dataframe in streamlit

Time:02-02

import streamlit as st
import pandas as pd


data = {'Days': ["Sunday", "Wednesday", "Friday"],
        'Predictions': [433.11, 97.9, 153.65]}
df = pd.DataFrame(data)
st.write(df)

streamlit writes dataframe with four decimals by default, but i expected two decimals. With print() it produces the expected, and when st.write() is used it produces the below output:


    Days     | Predictions
-------------|-------------
0   Sunday   |  433.1100  |
1   Wednesday|  97.9000   |
2   Friday   |  153.6500  |

I tried:

df.round(2)

but it didn't help.

Desired output format:

    Days     | Predictions
-------------|-------------
0   Sunday   |  433.11    |
1   Wednesday|  97.90     |
2   Friday   |  153.65    |

CodePudding user response:

With the df.style.format() method, you can specify the desired number of decimal places to override the default behavior of pandas in streamlit.
Note: This approach only provides the desired output format but when working farther you will have to still use the original dataframe which is df.

formatted_df = df.style.format({"Predictions": "{:.2f}".format})
st.write(formatted_df)
# Or
# st.dataframe(formatted_df)
  • Related