代码之家  ›  专栏  ›  技术社区  ›  ggulgulia

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

  •  1
  • ggulgulia  · 技术社区  · 6 年前

    我需要写入一个csv文件,该文件有3-5行(行)的详细信息,接下来是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 回复  |  直到 6 年前
        1
  •  1
  •   Anton vBR    6 年前

    您可以使用字符串模板并离开 {} 将数据帧插入。整个事情变得更易读。有用的事情: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)))
    

    测试.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的数据