10

Going over the documentation https://plotly.com/python/table/ I wanted to plot a data frame as a table

The documentation suggested the following

df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/2014_usa_states.csv')

fig = go.Figure(data=[go.Table(
    header=dict(values=list(df.columns),
                fill_color='paleturquoise',
                align='left'),
    cells=dict(values=[df.Rank, df.State, df.Postal, df.Population],
               fill_color='lavender',
               align='left'))
])

fig.show()

However, my dataframe is kind big and I wanted a better way to input the values of the columns. Something that would be better than

....values=[df.Rank, df.State, df.Postal, df.Population]....

1 Answer 1

22

After a bit of search I found an easy replacement. Pandas allows converting a whole dataframe into a list of lists.

Simply replace the line with

df.transpose().values.tolist()

So the final code looks like this

df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/2014_usa_states.csv')

fig = go.Figure(data=[go.Table(
    header=dict(values=list(df.columns),
                fill_color='paleturquoise',
                align='left'),
    cells=dict(values=df.transpose().values.tolist(),
               fill_color='lavender',
               align='left'))
])

fig.show()

Reference

https://thispointer.com/pandas-convert-a-dataframe-into-a-list-of-rows-or-columns-in-python-list-of-lists/

2
  • 3
    I ran into the exact same problem. Greatly appreciate the answer. Works well.
    – klocey
    Oct 2, 2020 at 23:23
  • 2
    Thanks man, this solved a lot of pain for me :-) .transpose() does only work Panda Dataframes. If someone (like me) got another format in spark, just add .toPandas() in front of transpose and it works like a charm! Apr 10, 2021 at 7:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.