PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, August 28, 2022

[FIXED] How to convert column to rows

 August 28, 2022     csv, python-3.x     No comments   

Issue

I have csv file contain on 6 columns like this:

1 2 3 4 5 6 7 8
1 2 3 4 5 6 7 8 
1 2 3 4 5 6 7 8
1 2 3 4 5 6 7 8
1 2 3 4 5 6 7 8 
1 2 3 4 5 6 7 8

I need to convert this columns to rows to be like this:

1 1 1 1 1 1 
2 2 2 2 2 2
3 3 3 3 3 3
4 4 4 4 4 4
5 5 5 5 5 5
6 6 6 6 6 6
7 7 7 7 7 7
8 8 8 8 8 8

How can do that please?

This is input enter image description here

This is the output enter image description here


Solution

Try:

import csv

with open("input.csv", "r") as f_in, open("output.csv", "w") as f_out:
    reader = csv.reader(f_in, delimiter=" ")
    writer = csv.writer(f_out, delimiter=" ")

    writer.writerows(zip(*reader))

Contents of input.csv:

1 2 3 4 5 6 7 8
1 2 3 4 5 6 7 8 
1 2 3 4 5 6 7 8
1 2 3 4 5 6 7 8
1 2 3 4 5 6 7 8 
1 2 3 4 5 6 7 8

Contents of output.csv after the script run:

1 1 1 1 1 1
2 2 2 2 2 2
3 3 3 3 3 3
4 4 4 4 4 4
5 5 5 5 5 5
6 6 6 6 6 6
7 7 7 7 7 7
8 8 8 8 8 8


Answered By - Andrej Kesely
Answer Checked By - Katrina (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing