Edit pandas dataframe in flask html page Edit pandas dataframe in flask html page flask flask

Edit pandas dataframe in flask html page


You can make use of df.style (a Styler instance) to render a DataFrame as a grid of HTML inputs.

np.random.seed(0)df = pd.DataFrame(np.random.randint(0, 100, (3, 3)))df.style.format('<input name="df" value="{}" />').render()

This will render as

HTML table

If you wrap the result in a <form> and submit it to some endpoint, the request query string (or POST body) will look like

df=44&df=47&df=64&df=67&df=67&df=9&df=83&df=21&df=36 

Note that these are the cells of the data frame in row-major order. At this point, you can re-create the data frame using

df = pd.DataFrame(np.asarray(request.values.getlist('df'), dtype=np.int).reshape((3, 3)))

As you suggested in your comment, another approach is to name HTML inputs with the column name, to avoid having to reshape the data.

def html_input(c):    return '<input name="{}" value="{{}}" />'.format(c)df.style.format({c: html_input(c) for c in df.columns}).render()

The data sent to the server will then look like

0=44&1=47&2=64&0=67&1=67&2=9&0=83&1=21&2=36

and you can restore the data frame using

df = pd.DataFrame(request.values.lists())

This is more elegant than the above, apart from the need to create the formatter dictionary {c: html_input(c) for c in df.columns}. Unfortunately, the formatter function is only passed the value, and none of the index information.