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.
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)
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
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)
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)
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...")
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
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.