Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to combine every 4 lines in a txt file?

I have a txt.file that looks like this:

data1  data2  data3  
data4  data5  data6  
data7  data8  data9  
data10 data11 data12 
data13 data14 data15 
data16 data17 data18 
data19 data20 data21
data22 data23 data24 
.
.
.

and I want to rearrange my txt file so that from data1 to data12 will be 1 line, and data13 to data24 will be second line and so on so forth. It is basically combining every 4 lines into 1 line. Desired output should look like this:

I desire something like this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

data1  data2  data3  data4  data5  data6  data7  data8  data9  data10 data11 data12 
data13 data14 data15 data16 data17 data18 data19 data20 data21 data22 data23 data24

How can I do this in Python?

Thank you for any advices,
Baris

I tried methods shared under various posts but none of them actually worked.

>Solution :

If you have a number of items to form a rectangular array, you can use a numpy reshape:

N = 4
df = pd.read_csv('your_file', sep='\s+', header=None)
df2 = pd.DataFrame(df.to_numpy().reshape(-1, N*df.shape[1]))

Else, a pandas reshape is needed:

N = 4
df = (pd.read_csv('your_file', sep='\s+', header=None)
   .stack(dropna=False).to_frame()
   .assign(idx=lambda d: d.index.get_level_values(0)//N,
           col=lambda d: d.groupby('idx').cumcount(),
          )
   .pivot(index='idx', columns='col', values=0)
   
)

Output:

       0       1       2       3       4       5       6       7       8       9       10      11
0   data1   data2   data3   data4   data5   data6   data7   data8   data9  data10  data11  data12
1  data13  data14  data15  data16  data17  data18  data19  data20  data21  data22  data23  data24
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading