pythonpandasdatatablerowflet

populate flet datatable with pandas dataframe


how can I disable pandas dataframe in flet datatable and be able to edit and delete each row.

Column A Column B
Cell 1 Cell 2
Cell 3 Cell 4

I tried setting the column headers by calling

df.column 

but I don't know how to go about populating the row


Solution

  • I've taken the code from another answer and reworked it quite a bit. I'm not sure if I'm unpacking the pandas dataframe in the most efficient way. Maybe someone with more experience can add to this.

    import flet as ft
    import pandas as pd
    
    df = pd.DataFrame({
            "test" : ['1', "20", "40"],
            "test1" : ['2', "21", "41"],
            "test2" : ['3', "22", "43"],
        })
    
    
    def headers(df : pd.DataFrame) -> list:
        return [ft.DataColumn(ft.Text(header)) for header in df.columns]
    
    def rows(df : pd.DataFrame) -> list:
        rows = []
        for index, row in df.iterrows():
            rows.append(ft.DataRow(cells = [ft.DataCell(ft.Text(row[header])) for header in df.columns]))
        return rows
    
                
    def main(page ft.Page):
        datatable = ft.DataTable(
            columns=headers(df),
            rows=rows(df))
        
        page.add(datatable)
    
    ft.app(target=main)