How to convert columns to rows(seperated by comma) in Python(or R,linux)
3
0
Entering edit mode
3.9 years ago
szp770 ▴ 10

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 • 5.0k views
ADD COMMENT
2
Entering edit mode
3.9 years ago
Mensur Dlakic ★ 28k

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)
ADD COMMENT
0
Entering edit mode
3.9 years ago
shoujun.gu ▴ 350

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

ADD COMMENT
0
Entering edit mode

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

ADD REPLY
0
Entering edit mode

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.

ADD REPLY
0
Entering edit mode
3.9 years ago
szp770 ▴ 10

ok, I got an answer:

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

print(','.join(lis))
ADD COMMENT

Login before adding your answer.

Traffic: 2670 users visited in the last hour
Help About
FAQ
Access RSS
API
Stats

Use of this site constitutes acceptance of our User Agreement and Privacy Policy.

Powered by the version 2.3.6