使用动态CSV命名将循环导出到CSV

时间:2019-07-17 00:30:42

标签: python pandas for-loop export-to-csv

我对Python相对较新(我的大部分经验是在SAS上),所以请多多包涵。

我正在尝试从现有数据集中创建许多CSV,并根据定义的列表将其导出。 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)] #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")

请注意,cc(AD-1,AD-2和AD-3)中的值包含在“费用”中

我得到的唯一错误是在这里:

table1_cc.to_csv(r“ C:\ Users \ etc \” + cc +“。csv”)

我得到的错误是: TypeError:只能将str(而不是“ list”)连接到str

输出应为3个文件:table1_AD-1.csv,table1_AD-2.csv和table1_AD-3.csv,并且每个文件都应包含每个文件的总和(同样,该部分有效。真正的问题是循环遍历并将cc中每个单独值的输出导出为CSV)。

感谢任何帮助!

2 个答案:

答案 0 :(得分:2)

您需要更改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")

答案 1 :(得分:0)

您还可以像这样遍历cc列表:

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))