简体   繁体   中英

How do I swap rows/columns in csv python

My raw csv file like this .

ID,SCORE1,SCORE2
1101110061,50,75
70,1101110062,80
85,52,1101110063

How do I swap score1 and score2 into the ID column?

Using csv or pandas but csv is preferred.

To swap the rows and columns, read the file in as a list of rows. Write them back out using zip(*data) .

Try the following example:

import csv

with open('input.csv') as f_input:
    data = list(csv.reader(f_input))
    
with open('output.csv', 'w', newline='') as f_output:
    csv_output = csv.writer(f_output)
    csv_output.writerows(zip(*data))

Giving you:

ID,1101110061,70,85
SCORE1,50,1101110062,52
SCORE2,75,80,1101110063

This 'trick' will create a list of columns from a list of rows, ie transpose the data.


If you just want to change the column order:

import csv

with open('input.csv') as f_input:
    data = list(csv.reader(f_input))
    
with open('output.csv', 'w', newline='') as f_output:
    csv_output = csv.writer(f_output)
    
    for row in data:
        csv_output.writerow([row[1], row[2], row[0]])

Giving you:

SCORE1,SCORE2,ID
50,75,1101110061
1101110062,80,70
52,1101110063,85

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