Start New Discussion within our Software Development Community

I want to read a file and convert the columns to rows.


A 1 2 3 4 5 6 7 8 9 10
B 11 12 13 14 15 16 17 18 19 20
C 21 22 23 24 25 26 27 28 29 30

want them to be like this:
A B C
1 11 21
2 12 22
3 13 23
4 14 24
5 15 25


I tried this but does not work

for J in range (0, 6):
        
        RR2 = (fields[J].rstrip())
        print >>ofh, RR2

please your help is need

The jargon for this is "transpose a matrix".

I did this interactively (pay careful attention to the brackets):

>>> import numpy
>>> M = numpy.matrix([['A', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10'],
... ['B', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20'],
... ['C', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30']])
>>> M
matrix([['A', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10'],
        ['B', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20'],
        ['C', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30']],
       dtype='|S2')
>>> Mt = M.transpose()
>>> Mt
matrix([['A', 'B', 'C'],
        ['1', '11', '21'],
        ['2', '12', '22'],
        ['3', '13', '23'],
        ['4', '14', '24'],
        ['5', '15', '25'],
        ['6', '16', '26'],
        ['7', '17', '27'],
        ['8', '18', '28'],
        ['9', '19', '29'],
        ['10', '20', '30']],
       dtype='|S2')
>>>

You'll need to rework the input and output, but that's nothing a couple for loops won't fix. Oh, and you may need to download numpy, but it's free and always worth having around.

This article has been dead for over six months. Start a new discussion instead.