将DataFrame写入CSV,为Pandas中的行名添加头名称

2024-09-28 22:25:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下数据帧:

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)

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

^{pr2}$

我要做的是将行名称的列命名为 最终创建的文件(tmp.csv版)公司名称:

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

怎么做?在


Tags: 文件csv数据inimport名称pandasdf
1条回答
网友
1楼 · 发布于 2024-09-28 22:25:15

感谢布伦巴恩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)

相关问题 更多 >