Home > Back-end >  Loop through a Pandas dataframe row by row and Include value of the dataframe as part of the file na
Loop through a Pandas dataframe row by row and Include value of the dataframe as part of the file na

Time:03-26

I am trying to export each row of a dataframe to generate separate csv files. I created a loop to go through each row. The file name will be the currency value of the respective row the current date as the file name. I have 4 rows in the dataframe and expect to have four csv file outputs. For example, for GBP, the result should generate the file name like "GBP_20220326.csv" and the csv file content will have two values "GBP,1.232".

I am stuck with one point on how to get the currency value (e.g. GBP to be part of the file name. Greatly appreciated if anyone can give me some guidance on this, many thanks.

>import numpy as np
>import pandas as pd
>from datetime import datetime

>rate = {"Currency":["EUR","GBP","JPY","AUD"],
        "Rate":[1.11,1.232,120,0.73],
       }
>df = pd.DataFrame(rate)
>df

>for i in range(0, len(df)):
> df.iloc[i:i 1].to_csv(df.iloc[0]   datetime.now().strftime("%Y%m%d")   '.csv', index=False, header=True)

#This last line was not working as planned.

CodePudding user response:

Try using df.iterrows:

today = date.today().strftime('%Y%m%d')
for _, row in df.iterrows():
    row.to_frame().T.to_csv(f"{row['Currency']}_{today}.csv", index=None)

Output:

>>>            
  • Related