How to add records to a dataframe using python and streamlit

I have a python code that allow user to read dataframe and add new records by enter data in the text input and on the click event the system append the new record to the datafarme

The problem is that when user click on the add button the system add the values in new column where each value is a considerate as new record.

while what i want is to consider all entered value are in the same record on different columns.

enter image description here

code:

import pandas as pd
import streamlit as st

df = pd.read_csv(iris.csv)

num_new_rows = st.sidebar.number_input("Add Rows",1,50)                
with st.form(key='add_record_form',clear_on_submit= True):
     st.subheader("Add Record")
     ncol = len(df.columns)
     cols = st.columns(int(ncol))
     for i, x in enumerate(cols):
            for j, y in enumerate(range(int(num_new_rows))):
                  records_val = x.text_input(f"{df.columns[i]}", key=j)
                  records_val_list.append(records_val)
                  newrow = pd.DataFrame(records_val_list)

            if st.form_submit_button("Add"):
                 df = pd.concat([newrow,df],ignore_index=True)
st.write(df)

You could use:
df.loc[len(df.index)] = [“df col heading1”, “df col heading2”…]

what did you mean [" df col heading1","df col heading2"...]

df col heading1 is your dataframe column heading #1, and so on…

Hope that helps…

based on your answer the code becomes like this ??

num_new_rows = st.sidebar.number_input("Add Rows",1,50)

with st.form(key='add_record_form',clear_on_submit= True):

           st.subheader("Add Record")

            ncol = len(df.columns)

            cols = st.columns(int(ncol))

            for i, x in enumerate(cols): # Creating one record loop

                    for j, y in enumerate(range(int(num_new_rows))):                            

                          records_val = x.text_input(f"{df.columns[i]}", key=j)

                    records_val_list.append(records_val) # adding row to list

            if st.form_submit_button("Add"):

                 df.loc[len(df.index)] = [df.columns]    
st.write(df)

but the system crash and display the below error:



    raise ValueError("cannot set a row with mismatched columns")
ValueError: cannot set a row with mismatched columns

Here’s the entire code. Copy-paste into a new file and run it. Modify it further as necessary
.
Cheers :slight_smile:

import streamlit as st
import pandas as pd

if "df" not in st.session_state:
    st.session_state.df = pd.DataFrame(columns=["Sepal Length", 
                                                "Sepal Width", 
                                                "Petal Length", 
                                                "Petal Width", 
                                                "Variety"])

st.subheader("Add Record")

num_new_rows = st.sidebar.number_input("Add Rows",1,50)
ncol = st.session_state.df.shape[1]  # col count
rw = -1

with st.form(key="add form", clear_on_submit= True):
    cols = st.columns(ncol)
    rwdta = []

    for i in range(ncol):
        rwdta.append(cols[i].text_input(st.session_state.df.columns[i]))

    # you can insert code for a list comprehension here to change the data (rwdta) 
    # values into integer / float, if required

    if st.form_submit_button("Add"):
        if st.session_state.df.shape[0] == num_new_rows:
            st.error("Add row limit reached. Cant add any more records..")
        else:
            rw = st.session_state.df.shape[0] + 1
            st.info(f"Row: {rw} / {num_new_rows} added")
            st.session_state.df.loc[rw] = rwdta

            if st.session_state.df.shape[0] == num_new_rows:
                st.error("Add row limit reached...")

st.dataframe(st.session_state.df)

i tried your answer it display the below error:


   StreamlitAPIException: The input argument to st.columns must be either a positive integer or a list of positive numeric weights. See documentation for more information.
    Traceback:

    File "F:\AIenv\streamlit\app2.py", line 1580, in <module>
        main()
    File "F:\AIenv\streamlit\app2.py", line 479, in main
        cols = st.columns(ncol)

I tried the code at my end - it works.

The error is due to ncol not being a positive integer or the data frame df not being initialized - red line after the import statements.

I am reproducing the earlier code here as I see it is not displaying fully. Copy it into a new file and try it, before you add it into your program.

Blockquote

import streamlit as st
import pandas as pd

if “df” not in st.session_state:
st.session_state.df = pd.DataFrame(columns=[“Sepal Length”,
“Sepal Width”,
“Petal Length”,
“Petal Width”,
“Variety”])

st.subheader(“Add Record”)

num_new_rows = st.sidebar.number_input(“Add Rows”,1,50)
ncol = st.session_state.df.shape[1] # col count
rw = -1

with st.form(key=“add form”, clear_on_submit= True):
cols = st.columns(ncol)
rwdta =

for i in range(ncol):
    rwdta.append(cols[i].text_input(st.session_state.df.columns[i]))

# you can insert code for a list comprehension here to change the data (rwdta) 
# values into integer / float, if required

if st.form_submit_button("Add"):
    if st.session_state.df.shape[0] == num_new_rows:
        st.error("Add row limit reached. Cant add any more records..")
    else:
        rw = st.session_state.df.shape[0] + 1
        st.info(f"Row: {rw} / {num_new_rows} added")
        st.session_state.df.loc[rw] = rwdta

        if st.session_state.df.shape[0] == num_new_rows:
            st.error("Add row limit reached...")

st.dataframe(st.session_state.df)

Blockquote

yes you were right your code is working the problem was with the file type that i upload where streamlit maybe has changed the file type for csv where it was : application/vnd.ms-excel
Now its : text/csv

for this reason the app was crashing.

Now i have another question once i add a new record the type of all columns is converted to object type

You can change types as required. Do it once for whichever column’s type you want to change.

You can refer the following link or Google further as required.

Cheers

Yes i know about the conversion of types but the problem is that once i add the new record the hall dataframe is converted to object

For this i have 2 questions

Q1)
WHAT CAN CONVERT THE COLUMN TYPE?
Q2)
CAN I SAVE THE TYPE OF THE READED FILE AND ASSIGNED TO THE DATAFRAME EACH TIME I UPDATE THE DATAFRAME ?

A1: I assume Pandas does it based on its assessment of the value it needs to store. I am not sure. You can go through the pandas documentation for that.

A2: Yes, you can…

Cheers