Qs about column_config

Hi,

I have the following code, running locally.

I have a dataframe with 2 columns:

  1. Amount (which I want to limit to 2 decimal places for entry and display), and
  2. Date (which I want in the format DD-MMM-YYYY for entry and display).

I can’t seem to accomplish this even though I try to format the dataframe as well as, additionally, use the column_config.

import streamlit as st
import pandas as pd

ColumnNames = ["Amount", "DOB"]
ColumnDataTypes = ["dec2", "dt"]  # 2 decimals & only date

xdf = pd.DataFrame(columns = ColumnNames)
cfg = {}

for i, col_fmt in enumerate(ColumnDataTypes):
  if col_fmt.lower().startswith("dec"): 
    dpstn = int(col_fmt[3:])
    xdf[ColumnNames[i]] = xdf[ColumnNames[i]].astype(float)
    cfg[f'col{i}'] = st.column_config.NumberColumn(label=ColumnNames[i], format=f"%.{dpstn}f")

  if col_fmt.lower() == "dt": 
    xdf[ColumnNames[i]] = pd.to_datetime(xdf[ColumnNames[i]], format='%d-%b-%Y')
    cfg[f'col{i}'] = st.column_config.DateColumn(label=ColumnNames[i], format="DD-MMM-YYYY")


st.caption("data editor")
xdf = st.data_editor(xdf, num_rows='dynamic', column_config=cfg, hide_index=True)
    
st.caption("dataframe")
st.dataframe(xdf)

I am using:
Streamlit Version: 1.27.0
Python Version: 3.11.4

Thanks in advance

streamlit-s-2023-11-09-19-11-72

The keys of your config need to be the names of the columns, not col0, col1, etc.

for i, col_fmt in enumerate(ColumnDataTypes):
  if col_fmt.lower().startswith("dec"):
    dpstn = int(col_fmt[3:])
    xdf[ColumnNames[i]] = xdf[ColumnNames[i]].astype(float)
    cfg[ColumnNames[i]] = st.column_config.NumberColumn(label=ColumnNames[i], format=f"%.{dpstn}f")

  if col_fmt.lower() == "dt":
    xdf[ColumnNames[i]] = pd.to_datetime(xdf[ColumnNames[i]], format='%d-%b-%Y')
    cfg[ColumnNames[i]] = st.column_config.DateColumn(label=ColumnNames[i], format="DD-MMM-YYYY")
1 Like

Omg, what an oversight :stuck_out_tongue:

Thanks @blackary, you are the best!!

Cheers

1 Like

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.