Display dataframe index name with Streamlit
Asked Answered
W

2

5

The following code does not display the name of the index:

import pandas as pd
import streamlit as st

df = pd.DataFrame(['row1', 'row2'], index=pd.Index([1, 2], name='my_index'))
st.write(df)

Dataframe without

Is there a way to have my_index displayed like you would do in a jupyter notebook?

enter image description here

Wrier answered 6/1, 2022 at 12:26 Comment(0)
A
3

According to the streamlit doc it will write dataframe as a table. So the index name is not shown.

To show the my_index name, reset the index to default and as a result the my_index will become a normal column. Add the following before st.write().

df.reset_index(inplace=True)

Output

enter image description here

Amphithecium answered 7/1, 2022 at 1:59 Comment(0)
C
4

I found a solution using pandas dataframe to_html() method:

import pandas as pd
import streamlit as st

df = pd.DataFrame(['row1', 'row2'], index=pd.Index([1, 2], name='my_index'))
st.write(df.to_html(), unsafe_allow_html=True)

This results with the following output:

Output1

If you want the index and columns names to be in the same header row you can use the following code:

import pandas as pd
import streamlit as st

df = pd.DataFrame(['row1', 'row2'], index=pd.Index([1, 2], name='my_index'))
df.columns.name = df.index.name
df.index.name = None
st.write(df.to_html(), unsafe_allow_html=True)

This results with the following output:

Output2

Note - if you have a large dataset and want to limit the number of rows use df.to_html(max_rows=N) instead where N is the number of rows you want to dispplay.

Cyclades answered 6/1, 2022 at 14:22 Comment(1)
For large dataframes the "to_html()" solution displays the whole thing while st.write(df) displays a scrollable table.Gaza
A
3

According to the streamlit doc it will write dataframe as a table. So the index name is not shown.

To show the my_index name, reset the index to default and as a result the my_index will become a normal column. Add the following before st.write().

df.reset_index(inplace=True)

Output

enter image description here

Amphithecium answered 7/1, 2022 at 1:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.