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

pandas how to add details to csv before writing a data frame

我需要写入一个包含 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) 对多行字符串使用 """ 和 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