Home  >  Q&A  >  body text

How does Python write the results of a loop into a csv file in column order?

A complete novice, I beg you all for help! !

import csv
with open('shiyan.csv', 'rb') as f:
    reader = csv.reader(f)
    your_list = list(reader)
    data = map(list,zip(*your_list))

    for i,data in enumerate(data):
         row = data
         row = map(eval, row)
         listA=row
         result=[float( sum(listA[i:i+10])/10) for i,num in enumerate(listA) if i%10==0]
         print result

The running results are as follows. Now I want to write the results obtained from each loop into a new csv file in sequence, but it is best to write them column by column. Thank you very much! ! ! ! ! ! !

过去多啦不再A梦过去多啦不再A梦2711 days ago1033

reply all(2)I'll reply

  • PHP中文网

    PHP中文网2017-05-18 10:50:34

    It is recommended that you put the data into the pandas dataframe and then call pandas.to_csv

    reply
    0
  • PHP中文网

    PHP中文网2017-05-18 10:50:34

    I changed your code, and the actual measurement can be obtained from a.csv复制到 b.csv

    import csv
    
    
    def foo():
    
        with open('a.csv', 'r') as f:
            reader = csv.DictReader(f)
            rows = [row for row in reader]
            
            if not rows:
                return 
            
            with open('b.csv', mode='w', newline='', errors='ignore') as f2:
                for index, row in enumerate(rows):
                    if index == 0:
                        f_csv = csv.DictWriter(f2, fieldnames=list(row.keys()))
                        f_csv.writeheader()
                    f_csv.writerow(row)
    
    
    if __name__ == '__main__':
        foo()
    

    If you don’t understand, you can ask again

    reply
    0
  • Cancelreply