pdubois
pdubois

Reputation: 7800

Appending a list to the top of Pandas DataFrame output

I have the following text file as input (infile.txt)

A foo 3.0
A bar 3.1
B foo 3.0
B bar 3.1

And with the following code

import pandas as pd

infile="infile.txt"
df = pd.io.parsers.read_table(infile,header=None,sep=" ")
df.columns = ['sample','celltype','score']
dfp = df.pivot(index='sample',columns='celltype',values='score')
dfp_prc =  dfp.applymap(lambda x: x * 100)
dfp_prc.to_csv("out.txt",sep=" ", index=True)

it produces this CSV:

sample bar foo
A 310.0 300.0
B 310.0 300.0

What I want to do then, is given a list:

mlist = ['sample','XXX','YYY']

I would like to obtain final CSV file that looks like this:

sample XXX YYY
sample bar foo
A 310.0 300.0
B 310.0 300.0

What's the convenient way to do it in Pandas?

Upvotes: 1

Views: 333

Answers (1)

eumiro
eumiro

Reputation: 212885

to_csv accepts a filename or a buffer (opened file) as well, so instead of

dfp_prc.to_csv("out.txt",sep=" ", index=True)

use

import csv

...

mlist = ['sample','XXX','YYY']
sep = ' '
with open('out.txt', 'w') as f:
    csv.writer(f, delimiter=sep, lineterminator='\n').writerow(mlist)
    dfp_prc.to_csv(f, sep=sep, index=True)

So you open a file, use csv.writer to insert a line and then into the same opened files you export the DataFrame.

Upvotes: 3

Related Questions