我对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)包含在“charge”中
我得到的唯一错误是:
table1_cc.to_csv(r"C:\Users\etc\"+cc+".csv")
我得到错误是: TypeError:只能将字符串(而不是"list")连接到字符串
输出应该是3个文件: table1_AD-1.csv、table1_AD-2.csv和table1_AD-3.csv,并且每个文件都应该分别包含每个文件的相加值(同样,该部分可以工作。真正的问题是循环遍历并将每个单独cc值的输出导出到CSV )。
感谢您的帮助!
发布于 2019-07-17 08:33:43
您需要更改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")发布于 2019-07-17 08:36:25
你也可以像这样遍历你的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))https://stackoverflow.com/questions/57067040
复制相似问题