How to integrate a function into a loop?

I have a function which works fine. I download some csv files which are named after cities and I enter the functionname(cityname) and the function processes the data and gives me a plotly figure. Since I have many cities and don’t want to to it by hand I want to interate through a list with the citynames. I just put a for loop outside of my function and it doesn’t work and I don’t know why. Whithout the loop the function works perfectly fine. Any ideas how I can loop thorugh the citynames?

It looks like this:

for cityname in list_of_names:
    def transformcsv_toplot(cityname):
        df = pd.read_csv(f'Input\{cityname}.csv', sep=";", index_col=[0])
        df = df.sort_index()
        dff = df.unstack().reset_index()
        dff.columns=['datetime', 'category']
        dff = dff.set_index('datetime')
        fig = px.scatter(dff, color='category')
    
        return fig.write_html(f'Graph/{cityname}_monthlydata.html')

My csv files are located in a seperate folder "input". The csv files have the city name and after some processing I now have a list with the citynames like this:

list_of_names = ['london', 'Liverpool', 'Paris']

>Solution :

Your function definition must be outside the for loop. You just need to call it inside the loop.

def transformcsv_toplot(cityname):
        df = pd.read_csv(f'Input\{cityname}.csv', sep=";", index_col=[0])
        df = df.sort_index()
        dff = df.unstack().reset_index()
        dff.columns=['datetime', 'category']
        dff = dff.set_index('datetime')
        fig = px.scatter(dff, color='category')
    
        return fig.write_html(f'Graph/{cityname}_monthlydata.html')

for cityname in list_of_names:
        transformcsv_toplot(cityname)

Leave a Reply