将列表追加到Pandas DataFrame输出的顶部 [英] Appending a list to the top of Pandas DataFrame output

查看:167
本文介绍了将列表追加到Pandas DataFrame输出的顶部的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下文本文件作为输入(infile.txt)

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

并使用以下代码

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)

它生成此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']

我想获得最终的CSV文件,如下所示:

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

在Pandas中最方便的方法是什么?

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

推荐答案

to_csv也接受文件名或缓冲区(打开的文件),因此代替

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

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

使用

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)

因此,您打开一个文件,使用csv.writer插入一行,然后将相同的文件导出到DataFrame中.

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

这篇关于将列表追加到Pandas DataFrame输出的顶部的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆