So, I have a dataframe similar to the image attached. Is it possible to exclude the ‘Total’ row from sorting, I have look at the documentation of st.dataframe but there it is not specified how to exclude certain row while sorting
Hi @Ameen
This can be done by using data slicing.
To exclude the last row of your DataFrame df
, you can use:
df[:-1]
Hope this helps!
Hi @dataprofessor, thank you for your response. However, my intention isn’t to remove the row from being displayed rather, I’m looking to exclude it from the sorting process… while using st.dataframe , it offers built-in sorting for each column, but I want to prevent the row labeled ‘Total’ from being affected by this sorting. Is there a way to achieve that?
When I use the built-in sorting feature of st.dataframe
, it correctly sorts the values. However, I would like to exclude the ‘Total’ row from sorting; I need it to stay at the bottom when sorting is applied. Is there a way to achieve this?
Hey @Ameen . Then first subset the data except the last row and sort the remaining dataframe at last add the last two the sorted dataframe.
Hope it works well !!!
Happy Streamlit-ing
Thanks for the reply, could you please provide a code example? I didn’t fully understand your explanation.
Hey @Ameen . Here is an demo:-
import pandas as pd
data = {
'a': [54, 24, 78],
'b': [104, 78, 182],
'c': [324, 56, 380]
}
df = pd.DataFrame(data,index=['q1','q2','total'])
print('Before:\n',df)
df1=df.copy()
df=df1.iloc[:-1,:].sort_values(by=['a','b','c'],ignore_index=True)
df.loc[len(df.index)]=df1.loc['total']
df.rename(index={0:'q1',1:'q2',2:'total'},inplace=True)
print('-'*10)
print('After:\n',df)
Output:-
Before:
a b c
q1 54 104 324
q2 24 78 56
total 78 182 380
----------
After:
a b c
q1 24 78 56
q2 54 104 324
total 78 182 380
Hope you understood now !
Happy Streamlit-ing
Hi @Guna_Sekhar_Venkata, thank you for your reply. I was hoping to find a solution using st.dataframe, but it seems that’s not possible. I will have to use the workaround you shared. Thanks again…
if anyone is struggling with similar issue use streamlit-aggrid, it provide way more table configuration that st.dataframe
from st_aggrid import AgGrid, ColumnsAutoSizeMode, GridUpdateMode, JsCode
from st_aggrid.grid_options_builder import GridOptionsBuilder
# pass your dataframe inside gridoptionbuilder
gob = GridOptionsBuilder.from_dataframe(df)
pinned_row_data = [df[df["Quarter"] == "Total"].to_dict(orient="records")[0]]
df = df.drop(df[df["Quarter"] == "Total"].index)
height = 180
gob.configure_grid_options(pinnedBottomRowData=pinned_row_data)
gridOptions = gob.build()
AgGrid(df, height=height, gridOptions=gridOptions, fit_columns_on_grid_load=True,update_mode=GridUpdateMode.VALUE_CHANGED)
Using this sample code, you can pin a row to ensure it remains excluded during sorting and filtering operations.
This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.