将DataFrame写入CSV,并在Pandas中为行名称添加标题名称

时间:2014-11-21 05:19:04

标签: python pandas

我有以下数据框:

In [18]: import pandas as pd
In [32]:  df = pd.DataFrame.from_items([("A\tbar", [1, 2, 3]), ("B\tfoo" , [4, 5, 6])],orient='index', columns=['one', 'two', 'three'])

In [33]: df
Out[35]: 
   one  two  three
A\tbar    1    2      3
B\tfoo    4    5      6

In [34]: df.to_csv("tmp.csv" , sep='\t', encoding='utf-8', doublequote=False)

最终的书面文件如下所示(注意行名称中的双引号也存在,我们想删除它):

In [34]: !cat tmp.csv
    one two three
"A  bar"    1   2   3
"B  foo"    4   5   6

我想要做的是命名如下所示的行名称的列 最终创建的文件(tmp.csv):

alpha othername one two three
A   bar     1   2   3
B   foo     4   5   6

这样做的方法是什么?

1 个答案:

答案 0 :(得分:1)

感谢BrenBarn index=False

df = pd.DataFrame.from_items([("A\tbar", [1, 2, 3]), ("B\tfoo" , [4, 5, 6])],orient='index', columns=['one', 'two', 'three'])
df['col_a'] = df.index
lista = [item.split('\t')[0] for item in df['col_a']]
listb = [item.split('\t')[1] for item in df['col_a']]
df['col_a'] = lista
df['col_b'] = listb
cols = df.columns.tolist()
cols = cols[-2:] + cols[:-2]
df = df[cols]
df.to_csv('filename', index=False)