Home > front end >  insert separator in data frame
insert separator in data frame

Time:06-08

I am concatenating the multiple data frame one below another and i get the results like

1.094  1.128  1.439 
3.064  3.227  3.371  
5.131  5.463  5.584  
3.650  3.947  4.135   
1.895  1.954  2.492 
5.307  5.589  5.839

I want to put some separator in between the concatenated files so that expected output should be

>
1.094  1.128  1.439 
3.064  3.227  3.371
>  
5.131  5.463  5.584  
3.650  3.947  4.135
>   
1.895  1.954  2.492 
5.307  5.589  5.839
>

My code

import numpy as np
import pandas as pd
#did some calcln and got x y z
df=pd.concat([x,y,z], axis=0)
df.to_csv('out.csv', index=False, header=False,sep='\t')

I hope experts may help doing this.Thanks in advance.

CodePudding user response:

You don't need to concat, the easiest if to save each dataframe after the other:

dfs = [x, y, z]

with open('out.csv', 'w') as f:
    for d in dfs:
        f.write('>\n')
        d.to_csv(f, header=False, index=False, sep='\t')
    # f.write('>') uncomment if you want a trailing ">"

output:

>
1.094   1.128   1.439
3.064   3.227   3.371
>
5.131   5.463   5.584
3.65    3.947   4.135
>
1.895   1.954   2.492
5.307   5.589   5.839

With ID:

dfs = {'x': x, 'y': y, 'z': z}

with open('out.csv', 'w') as f:
    for ID, d in dfs.items():
        f.write(f'>{ID}\n')
        d.to_csv(f, header=False, index=False, sep='\t')
    # f.write('>') uncomment if you want a trailing ">"
  • Related