编写csv(pandas.DataFrame.to_csv)时跳过第一行 [英] Skip first rows when writing csv (pandas.DataFrame.to_csv)
问题描述
在我的python脚本中,我正在通过以下方式读取csv文件
In my python script I am reading a csv file via
df = pd.read_csv('input.csv', sep=';', encoding = "ISO-8859-1", skiprows=2, skipfooter=1, engine='python')
我跳过了csv文件中的前两行,因为它们只是我不需要的说明。
I am the skipping the first two rows in the csv file because they are just discriptions I don't need.
导入后,我正在过滤和分离数据。 我想将数据写回到csv文件中,同时使用与以前相同的格式(前两行为空或说明与导入之前相同)。我该怎么办?
After importing, I am filtering and separating the data. I want to write the data back to csv files while having the same format as before (first two rows either empty or the description as before the import). How can I do that?
当前我正在使用
df.to_csv('output.csv'), sep=';', encoding = "ISO-8859-1")
是否有要导出的参数 skiprows?我在 api文档中找不到一个。 to_csv 。
Is there something like a parameter "skiprows" for exporting? I can't find one in the api documentation for .to_csv.
推荐答案
一种可能的解决方案是使用 NaN $ c $编写DataFrame c> s,然后附加原始
DataFrame
:
One possible solution is write DataFrame with NaN
s first and then append original DataFrame
:
df1 = pd.DataFrame({'a':[np.nan] * 2})
df1.to_csv('output.csv', index=False, header=None)
df.to_csv('output.csv', sep=';', encoding = "ISO-8859-1", mode='a')
或与 df1
相同的原始标头,并且首先写入,只需要标头数据中没有值 |
:
Or same original header to df1
and this write first, only necessary no value |
in header data:
df1 = pd.read_csv('input.csv', sep='|', encoding = "ISO-8859-1", nrows=2, names=['tmp'])
df1.to_csv('output.csv', index=False, header=None)
df.to_csv('output.csv', sep=';', encoding = "ISO-8859-1", mode='a')
这篇关于编写csv(pandas.DataFrame.to_csv)时跳过第一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!