首页 > 解决方案 > 如何将数据框导出到现有的格式化 csv 文件?

问题描述

我正在尝试将数据框导出到现有的格式化 csv 文件,但数据框继续以垂直形式附加,以及应该水平的附加标题。

A B C D E F
1 2 3 4 5 6   #=-> This is the format I have in my exisiting csv file

A B C D E F
1 2 3 4 5 6
x x x x x x   #-> This is how I want to do it

A B C D E F
1 2 3 4 5 6
A 1
B 2
C 3 
D 4  #-> This is what's currently happening

任何帮助将非常感激。谢谢!

df.iloc[location].to_csv(path,mode='a')

这是我一直在尝试的代码。

标签: pythonpandascsv

解决方案


df.iloc[location]可以给你Series哪些不同的待遇DataFrame

您必须将其转换为DataFrame但使用列表Series来获取行而不是列中的数据

df = pd.DataFrame( [df.iloc[location]] )

然后保存到没有标题的csv

df.to_csv(path, mode='a', header=None)

编辑:您也可以转换SeriesDataFrame使用.to_frame(),然后使用.T将列转置为行

df = df.iloc[location].to_frame().T

推荐阅读