Link to home
Start Free TrialLog in
Avatar of ritesh singh
ritesh singh

asked on

How to transpose every n rows in python

I have a txt file containing data in following format:

abc 123 456
cde 45 32
efg 322 654
abc 445 856
cde 65 21
efg 147 384
abc 815 078
efg 843 286
and so on. How can transpose it into following format using Python:

abc 123 456 cde 45 32 efg 322 654
abc 445 856 cde 65 21 efg 147 348
abc 815 078 efg 843 286
Also, in case cde/efg is missing after abc, it should insert blank spaces instead, since it is a fixed width file.
One more thing , abc will always be present, sometimes row starting with cde or efg will not be there .
Avatar of aikimark
aikimark
Flag of United States of America image

will there be cases where both cde and efg will be missing?
Avatar of ritesh s
ritesh s

yes, there is a possibility where both cde and efg will be missing.
Also what if the sample file contains one additional key to be transposed(I have added hij as well and abc  key is mandatory and others such as cde, efg,hij can be missing and in case any of them is missing I want to insert blank spaces since it is fixed width file):

 abc 123 456
 cde 45 32
 efg 322 654
 hij 986 457
 abc 445 856
 cde 65 21
 efg 147 384
 hij 317 111
 abc 815 078
 efg 843 286
 abc 987 510
 cde 11 11

Desired output:
 abc 123 456 cde 45 32 efg 322 654 hij 986 457
 abc 445 856 cde 65 21 efg 147 384 hij 317 111
 abc 815 078                   efg 843 286                    
 abc 987 510 cde 11 11
Are the letter combinations going to be in ascending sequence, like you've shown in your data sample?
No, this is jz an example but then yes the occurrence pattern is fix likr first row as mentioned in example will be identified by lets say 'abc'
Please post a representative data sample.

You've just introduced "hij" into the set, so it is reasonable to assume that we aren't seeing a representative sample of the data and that your problem is more complicated than you've described.

You have also introduced an output format that makes certain assumptions about the underlying data.
Input :
abc 123 456
cde 45 32
efg 322 654
hij 684 321
abc 445 856
cde 65 21
efg 147 384
hij 789 321
abc 815 078
efg 843 286
abc 123 651
abc 647 215

Desired output :
abc 123 456cde 45 32efg 322 654hij 684 321
abc 445 856cde 65 21efg 147 384hij 789 321
abc 815 078         efg 843 286          
abc 123 651                                
abc 647 215                              

abc will always be considered as starting of new row.
ASKER CERTIFIED SOLUTION
Avatar of aikimark
aikimark
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
@ritesh

Where do you stand with this question?
Have you tested my code?
answers the question