Hlib Babii
Hlib Babii

Reputation: 680

Display dataframe index name with Streamlit

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

Upvotes: 6

Views: 3927

Answers (2)

ferdy
ferdy

Reputation: 5014

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

Upvotes: 3

RoseGod
RoseGod

Reputation: 1234

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.

Upvotes: 5

Related Questions