setting consistent column type for streamlit tables

I need to append rows of a serialized subclass of BaseModel and display in streamlit. The problem is that some fields are Optional and sometimes are missing. When they are missing, the column type will of the initialized table will deviate. I tried a few ways to pre-specify column types:

  • by setting them in the pandas.DataFrame that is used to initialize the streamlit.dataframe
  • by setting the column_config

None of these seem work (see code below). Any tips appreciated

Setup code

import pandas as pd
import numpy as np
from pydantic import  BaseModel
import streamlit as st
from functools import partial
from typing import Optional

class MyModel(BaseModel):
    first: str 
    second: Optional[str]
    date: datetime.datetime = datetime.datetime.today()

TYPE_TO_STREAMLIT = {"str": st.column_config.TextColumn,
'float': st.column_config.NumberColumn,
'int': partial(st.column_config.NumberColumn, format='%u.'),
'datetime64[D]': partial(st.column_config.DatetimeColumn, format='YYYY-MM-DD'),
'datetime64[s]': partial(st.column_config.DatetimeColumn, format='YYYY-MM-DD HH:mm:ss'),
}



def remove_optional(type_):
    """
    >>> remove_optional(typing.Optional[str])
    """
    match = re.search("Optional[(?P<t>[A-Z_a-z]+)]", repr(type_))
    if match:
        return match.groupdict()['t']
    elif 'date' in repr(type_):
        return 'datetime64[s]' # pandas does not support [D]
    elif type_ == str:
        return 'str'
    else:
        return (type_)


def np_from_base_model(bm: BaseModel):
    col_types = {kk: remove_optional(ff.annotation) for kk, ff in bm.model_fields.items()}
    # list(col_types.values())
    return np.empty(0, dtype=[tuple(tt) for tt in col_types.items()])

def df_from_base_model(bm: BaseModel):
    return pd.DataFrame(np_from_base_model(bm))

def st_from_base_model(bm: BaseModel):
    col_types = {kk: TYPE_TO_STREAMLIT[remove_optional(ff.annotation)](kk.replace('_', ' '))  for kk,ff in bm.model_fields.items()}
    df_ = df_from_base_model(bm)
    return st.dataframe(df_, column_config=col_types)


def format_metadata(report_metadatas: List[MyModel]) -> pd.DataFrame:
    bm = MyModel
    col_types = {kk:  remove_optional(ff.annotation) for kk, ff in bm.model_fields.items()}
    df_ = [md.model_dump() for md in report_metadatas]
    df_ = pd.DataFrame(df_)
    df_ = df_.astype(col_types)
    return df_

Actual code


st.session_state['df_reports'] = st_from_base_model(MyModel)


examples = [MyModel(**{"first":x, "second":chr(ord(x)+5) if ord(x)%2==0 else None}) for x in "hello world!"]

st.session_state['df_reports'] = st_from_base_model(MyModel)

for ex in examples:
     df_ = format_metadata([ex])
     st.session_state['df_reports'].add_rows(df_)
    #  time.sleep(5)

I am still getting:

Unsupported operation. The data passed into add_rows() must have the same data signature as the original data.

In this case, add_rows() received ["unicode","unicode","unicode","unicode","unicode","unicode","unicode","unicode","unicode","unicode","datetime","unicode"] 
but was expecting ["empty","empty","empty","empty","empty","empty","empty","empty","empty","empty","datetime","empty"].

or

elementType 'alert' is not a valid arrowAddRows target!

depending on the input data.

I am struggling to see how data is represented in streamlit and where I can see current types of the data (the code seems to be quite obscure).

2

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật