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

Hlib Babii
  • 599
  • 1
  • 7
  • 24

2 Answers2

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.

RoseGod
  • 1,206
  • 1
  • 9
  • 19
  • 1
    For large dataframes the "to_html()" solution displays the whole thing while st.write(df) displays a scrollable table. – LogZ Sep 13 '22 at 19:22
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

ferdy
  • 4,396
  • 2
  • 4
  • 16