简体   繁体   中英

How to include “for” loops variables within output.csv file

I am beginner in python programming and trying to find out how I can get my desired output from a code. I have a "for" loop within another "for" loop. I'm aiming to export a .csv file which includes the results of my code besides the details of those "for" loops variables corresponding to my results. I'm wondering how I can manipulate to.csv to gain what I need (please find below my desired output.csv file).

exemplary script

df1 = [1, 2, 3, 4, 5]
df2 = [I, II, III]
for i in df1.index:
    for j in df2.index:
        ### bunch of calculations happening here resulted in output###
output.to_csv(r'd:\project\output.csv')

my desired output.csv file

output     df1      df2
A          1        I
B          1        II
C          1        III
D          2        I
E          2        II
F          2        III
G          3        I
H          3        II
I          3        III
G          4        I
K          4        II
L          4        III
N          5        I
M          5        II
O          5        III

Try this (pandas):

import pandas as pd,string
l=[]
l2=[]
df1 = [1, 2, 3, 4, 5]
df2 = ['I', 'II', 'III']
for i in df1:
    for j in df2:
        l.append(i)
        l2.append(j)
output=pd.DataFrame({'output':string.ascii_uppercase[:len(l)],'df1':l,'df2':l2})
output.to_csv(r'd:\project\output.csv')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM