Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading