Why can't I add more formatting options to my dataframe?

29 views Asked by At

In my code I am able to white out N/As. You will see this near the bottom of the code.

I would also like to add additional formatting to specific columns whereby they are formatted as USD Currency ($, commas to separate thousands, no decimals).

import streamlit as st
import pandas as pd

st.set_page_config(page_title="Page Title", page_icon=":bar_chart:", layout="wide")
st.title("Analytics")
st.sidebar.success("Directory")

df = pd.read_excel(
        io="file.xlsx",
        engine="openpyxl",
        sheet_name="Sheet1",
        skiprows=1,
        usecols="B:L",
        nrows=60
)

st.markdown("### Detailed Data View")

df = df.style.highlight_null(props="color: transparent;")

st.table(df)

I have tried appending syntax such as df.style.format('{:.2f}') after the style syntax near but the bottom but it errors out. How can I append more formatting to my code?

Current data appearance

1

There are 1 answers

0
xArbisRox On

Finding the reason for it "erroring out" would be easier, if you provide the error code alongside your description. Generally speaking, you can apply as many styles to your Dataframe as you want.

You just have to so in the correct format and return the expected shape.

import pandas as pd
import numpy as np

df = pd.DataFrame(dict(a=[1,2,3,4,5], b=["hello", "how", "are", "you", "doing"], c=[np.nan for x in range(5)]))

    a   b   c
0   1   hello   NaN
1   2   how NaN
2   3   are NaN
3   4   you NaN
4   5   doing   NaN

style = df.style

def style_background(_cell):
    if isinstance(_cell, int):
        return 'background: green'
    elif isinstance(_cell, str):
        return 'background: red'
    

styled_df = style.applymap(style_background)
styled_df.format({'a': "{:.2f}"})
styled_df.highlight_null(props="color: yellow")

Styled