Skip to main content
 首页 » 编程设计

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

2025年05月04日10jyk

我有以下数据框:

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 

有什么方法可以做到?

请您参考如下方法:

感谢 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)