熊猫如何在写入数据框之前向csv添加详细信息

时间:2018-06-22 09:59:43

标签: python pandas export-to-csv

我需要写入一个具有3-5行(行)有关该文件的详细信息的csv文件,然后再插入3行空白行,然后才能附加到数据框。

这是文件的外观。 (注意:带有“#”的行是用于演示的注释)

some details
some more details
some details that were not covered in last two details
#blankline1
#blankline2
#blankline3
A1;B;C  #headers
1231;1241;abc
1232;1242;abd
1233;1243;abe
1234;1244;abf
.
.
.

这是我到目前为止尝试过的:

import pandas as pd

file_name = 'my_csv_file.csv'

df1 = pd.Dataframe({"some details":})
df2 = pd.DataFrame({"some more details":})
df3 = pd.DataFrame({"some details that were not covered in last two details'})
df4 = pd.DataFrame({"\n\n\n\":}) #write 3 blank lines
df5 = pd.DataFrame({"A":[1231 1232 1233 1234]
                    "B":[1241 1242 1243 1244]
                   "headers":[abc abd abe abf] }

df1.to_csv(file_name, sep=';', mode='a', index=False)
df2.to_csv(file_name, sep=';', mode='a', index=False)
df3.to_csv(file_name, sep=';', mode='a', index=False)
df4.to_csv(file_name, sep=';', mode='a', index=False)
df5.to_csv(file_name, sep=';', mode='a', index=False)

但是这似乎不起作用。有人可以帮我吗?

1 个答案:

答案 0 :(得分:1)

您可以使用字符串模板并保留{}以便将数据框插入其中。整个事情变得更具可读性。有用的操作:1)将"""用于多行字符串,以及2)使用注释来记住为什么要做某事。

import pandas as pd

df = pd.DataFrame({
    "A": [1231, 1232, 1233, 1234],
    "B": [1241, 1242, 1243, 1244],
    "C": ['abc', 'abd', 'abe', 'abf']
})

# Setups the template that the client requested with 3-5 rows of information 
# Followed by 3 blank rows and the dataframe
template = """\
some details
some more details
some details that were not covered in last two details



{}"""

with open('test.txt', 'w') as fp:
    fp.write(template.format(df.to_csv(index=False)))

test.csv:

some details
some more details
some details that were not covered in last two details


A,B,C
1231,1241,abc
1232,1242,abd
1233,1243,abe
1234,1244,abf

注意:来自用户Taras的数据