Convert CSV into Dataframe using FileInput

Hello. I’m trying to convert a csv to dataframe using FileInput. Can I somehow read the csv directly into the dataframe, or do I need first reading the csv with BytesIO?

The below attempt failed with error message “EmptyDataError: No columns to parse from file”. The FileInput widget did not appear, which seems to be part of the problem.

import io
import panel as pn

file_input = pn.widgets.FileInput(accept='.csv, .xls')
file_input

if file_input.value is not None:
    out = io.BytesIO()
    file_input.save(out)
    
df = pd.read_csv(out)

Blockquote

To convert the CSV to a DataFrame this should work pd.read_csv(io.BytesIO(file_input.value))

Screenshot from 2022-05-01 10-10-59

Thanks. The code works if the code is spread across multiple cells, but the error message will appear if the script is all in the same cell.

Simply speaking, how would I go about pausing execution of the fileinput while the user adds input to the csv file and then continue execution?

Maybe not the cleanest but this works:

import io
import panel as pn
import pandas as pd
pn.extension()

file_input = pn.widgets.FileInput(accept='.csv, .xls')
df = pn.widgets.DataFrame()

def load_csv(data):
    if data is not None:
        df.value = pd.read_csv(io.BytesIO(data))
        return df.value

f = pn.bind(load_csv, file_input.param.value)
pn.Column(file_input, f).servable()
2 Likes

Great, this appears to be the solution I am looking for. However, even after trying various csv files the output always looks wired. Any idea why?

You might need to share your csv here. It looks like possibly a delimiting issue.

Try this file: https://www.stats.govt.nz/assets/Uploads/Business-financial-data/Business-financial-data-December-2021-quarter/Download-data/business-financial-data-december-2021-quarter-csv.zip

The csv is comma-delimited, but the below approach does not work for me.

df.value = pd.read_csv(io.BytesIO(data), sep=’,’)

I think it is a sizing issue. Try: pn.extension(sizing_mode="stretch_width")

3 Likes