How to Transpose CSV/text File Python

If you want to transpose rows to columns in python of CSV or text file you can do it with method zip and two for loops. Let say that we have this file:

myfile.txt

1,Python,35,PyCharm
2,Java,28,IntelliJ
3,Javascript,15,WebStorm

And we want transposed output like:

1, 2, 3, 
Python, Java, Javascript, 
35, 28, 15, 
PyCharm, IntelliJ, WebStorm, 

This can be achieved with this code example:

with open('/home/user/myfile.txt') as file:
    lis = [x.replace('\n', '').split(',') for x in file]

for x in zip(*lis):
    for y in x:
        print(y + ', ', end="")
    print('')

First we are reading the file content row by row. Then we are splitting the elements using split(',') and separator ','. Finally we load this into list.

The second part of the code is using method zip to transpose the list - rows to columns. Finally we iterate over the transposed elements and print them out.

If you want to transpose simple text file divide by spaces you can check this code example:

with open('/home/user/myfile.txt') as file:
    lis = [x.replace('\n', '').split(',') for x in file]

# normal text file
for x in zip(*lis):
    for y in x:
        print(y+'\t', end='')
    print('')

Another way to transpose CSV or text file is by using module numpy which can transpose rows to columns and vice versa. The example below shows how numpy can transpose CSV file:

with open('/home/user/myfile.txt') as file:
    lis = [x.replace('\n', '').split(',') for x in file]

x = np.array(lis)

print(x)
print(x.T)

The output of this code is:

[['1' 'Python' '35' 'PyCharm']
 ['2' 'Java' '28' 'IntelliJ']
 ['3' 'Javascript' '15' 'WebStorm']]
[['1' '2' '3']
 ['Python' 'Java' 'Javascript']
 ['35' '28' '15']
 ['PyCharm' 'IntelliJ' 'WebStorm']]

Related Article