Using data of a CSV

Hi all,

Does somebody have an example of using a csv table as you would using a pandas df or dict?

I only found the following example below, but this is just to read one value of the cvs. Thanks!

class Controller(ViktorController):

def process_file(self, file: File, **kwargs):

    return {
        'tab': {
            'section' : {
                'number_of_entries': number_of_entries,
                'project_name': project_name

Hi Bart,

As you suggested, you can parse a csv using the Pandas library. The csv table is then converted into a DataFrame object from which you can extract any information that you can to store into your parametrization. Keep in mind that the parametrization of your entity can only include serializable objects, so no DataFrame but you can always convert your DataFrame into a dictionary.

from io import StringIO
import pandas as pd

def process_file(self, file: File, entity_id: int, **kwargs) -> dict:
        file_content = file.getvalue("utf-8")
        df = pd.read_csv(StringIO(file_content))  
        serialized_df = dataframe.to_dict()

    return {}

That easy! Thanks a lot. It saves me a lot of trails and errors :slight_smile:

1 Like

Hi Matthias,

Unfortunately I’m not able to use the dict in other functions of the controller (for example use data from the dict in a Plotly graph). I’ve tried Memoize, but I couldn’t get it working with the ParamsFromFile().

Any ideas?

Hi Bart,

The decorator @ParamsFromFile should allow you to save a dictionary into the parametrization of your entity. You can use a HiddenField (here) to store objects in params without having an UI Field connected on the editor.

You can then retrieve this dictionnary in any method of your controller with the params argument

class Parametrization(Parametrization):
    section.my_dict = HiddenField("UI name", name='my_dict')

class Controller(ViktorController):
    def process_file(self, file: File, **kwargs):
        # Insert project specific content: convert csv into serialized dict
        my_dict = ...
        return {'my_dict': my_dict} # The structure of this dictionnary should match your file

    def controller_method(self, params, entity_id, **kwargs):
        my_dict = params.my_dict # type is Munch at this point

Hi Matthijs,

Thanks for your clear answer. I couldn’t have thought of this myself. Thanks!