This is a test version of Biostars. For the public version, visit https://www.biostars.org.
How to convert columns to rows(seperated by comma) in Python(or R,linux)

Hi, all. Now I have a column of data seperated by '\n'.

ENCFF720NRD_POLR2G
0.492022341246791
0.49432683771391
0.498306209291954
0.499462572697776
0.501878178815989
0.505310232483092
0.50580816832688
0.508190853066991
0.515285410047909
0.520515793993818
0.527918988894439
0.539824182250468
0.54935080603865

how can I transfer the data to rows seperated by comma in python(or R,linux) like this:

ENCFF720NRD_POLR2G,0.492022341246791,0.49432683771391,0.498306209291954

Thanks!

r python linux sequencing seq

3 answers

There are many ways of doing this. Simple character translation:

tr "\n" "\," < file.csv > new_file.csv

Another python solution (column transposition):

import pandas as pd
df = pd.read_csv('file.csv')
df_tr = df.transpose()
df_tr.to_csv('new_file.csv', header=None)

all you need to do is replace '\n' to ','

Hi, I tried this with python. line.replace('\n',',').strip()

the result is like this: ENCFF720NRD_POLR2G, 0.492022341246791, 0.49432683771391, 0.498306209291954, 0.499462572697776, 0.501878178815989, 0.505310232483092, 0.50580816832688, 0.508190853066991, 0.515285410047909, these numbers are still in a column just with a comma at each of the end. however, I want these numbers being one row. How to do that? Thanks

You're not replacing \n with , - their suggestion is correct, your solution is wrong. You seem to have figured it out, but if the time between you asking a question and finding the answer yourself is ~3 hours, then you haven't really tried hard enough before asking, have you?

Please do your best before asking others to spend their time solving your problems.

ok, I got an answer:

lis=[]
for line in lines:
    line=line.strip('\n')
    lis.append(line)

print(','.join(lis))

Log in to answer this question.