How to select a file using FileInput, convert it into a DataFrame and access it?

I have the following code, which I would expect to work:

    uploadFile = pn.widgets.FileInput(accept=".csv")

    def get_data_from_file(file):
        return pd.read_csv(file)

    df = pn.bind(uploadFile, get_data_from_file)

    pn.serve(uploadFile)

I would now expect to have access to df, for example to plot in a panel or perform operations on in Python. However, this code runs without error and also does not create a df variable.

Hi @randomBloke,

Iā€™m not at my machine just now but if you try

dataframe = df()

I think you should get the df contents into dataframe. There might be a way to just return the value but I think as it is above it returns more.

Hope it helps

I tried that and it gives me the following error:

'NoneType' object is not callable

try this, note the difference here in pn.bind order:

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

uploadFile = pn.widgets.FileInput(accept=".csv")

def get_data_from_file(file):
    df = pd.read_csv(BytesIO(file))
    return df
    
df = pn.bind(get_data_from_file,uploadFile)

uploadFile
dataframe=df()

This gives me

Does not work for me. I added an if-statement at the beginning of get_data_from_file() to make sure I do not immediately run into an error.

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

uploadFile = pn.widgets.FileInput(accept=".csv")

def get_data_from_file(file):
    if file is not None:
         df = pd.read_csv(BytesIO(file))
         return df
  
df = pn.bind(get_data_from_file,uploadFile)
dataframe=df()
uploadFile

This code, however, create a dataframe of type NoneType. Without the if statement in the function I immediately get the error EmptyDataError: No columns to parse from file

for me the uploadFile has to come first, then dataframe =df() but I am running it all inside jupyter lab

OK, so I got it working. It seems that the line dataframe=df() has to be in a different cell in a jupyter notebook and indeed that cell has to come after uploadFile.

However, how would I then implement this in a Python file? So a .py file instead of .ipynb

For future reference, this code works:

1 Like