ZDR
ZDR

Reputation: 47

For loop export to CSV with dynamic CSV naming

I am relatively new to Python (most of my experience has been in SAS), so please bear with me.

I'm trying to create a number of CSVs from an existing dataset and export them based on a defined list. The naming of the CSVs should be dynamic based on the corresponding list value.

I've tried a lot of things - mostly stabbing in the dark - and nothing works. See code below

cc = ['AD-1','AD-2','AD-3'] #the list I want it to cycle through
for index in range(len(cc)): 
    df1_cc = df[df['charge'].isin(cc)] #df is predefined 
    #set "charge" as the index variable so you can aggregate on it           
    df1_cc = df1_cc.set_index('charge')
    df1_cc
    #sum up values based on individual values of 'charge'
    table1_cc = df1_cc.sum(level='charge')
    table1_cc
    #output to CSV
    table1_cc.to_csv(r"C:\Users\etc\table1_"+cc+".csv")

Note, the values in cc (AD-1, AD-2 and AD-3) are contained in 'charge' among others

The only error I get is here:

table1_cc.to_csv(r"C:\Users\etc\"+cc+".csv")

The error I get is: TypeError: can only concatenate str (not "list") to str

The output should be 3 files: table1_AD-1.csv, table1_AD-2.csv and table1_AD-3.csv, and each should contained summed values of each individually (again, that part works. The real issue is looping through and exporting to CSV the output for each individual value in cc).

Appreciate any help!

Upvotes: 2

Views: 786

Answers (2)

Nakor
Nakor

Reputation: 1514

You could also iterate through your cc list like this:

cc_list = ['AD-1','AD-2','AD-3'] #the list I want it to cycle through

for index,cc in enumerate(cc_list): 
    df1_cc = df[df['charge'].isin([cc])] #df is predefined 
    #set "charge" as the index variable so you can aggregate on it           
    df1_cc = df1_cc.set_index('charge')
    df1_cc
    #sum up values based on individual values of 'charge'
    table1_cc = df1_cc.sum(level='charge')
    table1_cc
    #output to CSV
    table1_cc.to_csv(r"C:\Users\etc\table1_{}.csv".format(cc))

Upvotes: 0

BENY
BENY

Reputation: 323306

You need to change the last line of to_csv

cc = ['AD-1','AD-2','AD-3'] #the list I want it to cycle through
for index in range(len(cc)): 
    df1_cc = df[df['charge'].isin([cc[index]])] #df is predefined 
    #set "charge" as the index variable so you can aggregate on it           
    df1_cc = df1_cc.set_index('charge')
    df1_cc
    #sum up values based on individual values of 'charge'
    table1_cc = df1_cc.sum(level='charge')
    table1_cc
    #output to CSV
    table1_cc.to_csv(r"C:\Users\etc\table1_"+cc[index]+".csv")

Upvotes: 2

Related Questions