Hops to import CSV file and output dataframe data in grasshopper canvas

I am working on “everything python” in the ghhops-server with flask for an app in grasshopper canvas. Hitting a wall with importing/reading csv files and outputting dataframes or series data on the grasshopper canvas. Any help would be most appreciated. Michael Wickerson

create a dataframe from a csv file using pandas

@hops.component(
“/panda_dataframe_csv”,
name=(“Panda Dataframe CSV”),
description=(“Panda Dataframe CSV”),
category=“panda”,
subcategory=“dataframe”,
inputs=[
hs.HopsFile(“csvFile”, “csvFile”, “csvFile”, access = hs.HopsParamAccess.FILE),
],
outputs=[
hs.HopsNumber(“panda_dataframe”, “panda_dataframe”, “panda_dataframe”, access = hs.HopsParamAccess.LIST),
]
)
def panda_dataframe(csvFile):
import pandas as pd
x = pd.read_csv(csvFile)
print(x)
return x

sorry, I can’t remember how to format the python code on the forum…

I figured out the first part for the inputs but I am still trying to figure out how to “output” data from dataframes, series, arrays, etc…, into the grasshopper canvas. Perhaps I should use HopsString on the outputs as well. Any help would be most appreciated. Michael wickeson

create a dataframe from a csv file using pandas

@hops.component(
“/panda_dataframe_csv4”,
name=(“Panda Dataframe CSV”),
description=(“Panda Dataframe CSV”),
category=“panda”,
subcategory=“dataframe”,
inputs=[
hs.HopsString(“csvFile”, “csvFile”, “csvFile”, access = hs.HopsParamAccess.ITEM),
],
outputs=[
hs.HopsNumber(“panda_dataframe”, “panda_dataframe”, “panda_dataframe”, access = hs.HopsParamAccess.LIST),
]
) Preformatted text
def panda_dataframe4(csvFile):
import pandas as pd
x = pd.read_csv(csvFile)
print(x)
return x

image

From my small experience with hops, I think you want to return the csv as a string with a custom separator to pass it between grasshopper components (I remember having problems when using default separators for some reasons).

Here under is a function to read csv and put it back in a dataframe (with a custom separator and some options)

def csv_to_df(df1):
    """load df from a csv, with special line-terminator"""
    buffer = io.StringIO(df1)
    loaded_df1 = pd.read_csv(filepath_or_buffer=buffer, skipinitialspace=True, lineterminator='@')
    return loaded_df1

Then whenever you’ve done what you needed with your DF, you need to convert it back to a csv, with the same custom separator

return the_actual_dataframe.to_csv(index=False, line_terminator='@')
1 Like

Here is a small plugin where I used dataframes between components, you might find some interesting bits :slight_smile:

1 Like

thank you, I am just trying to keep my head above water with hops :slight_smile:

thank you for this plug-in

1 Like

Your website is great and the github files really give me a lot to sink my teeth into as well. Thank you. Michael Wickerson