【问题标题】:Add a description to python dataframe before column headers when exporting?导出时在列标题之前向 python 数据框添加描述?
【发布时间】:2020-11-20 17:30:45
【问题描述】:

我有一个包含数千行数据的数据框,我将其导出为 txt。文件,然后可以在工作中导入到软件中。

其他软件读取数据的方式要求在数据框列标题之前找到文本的特定描述(分成行)。我正在使用以下代码导出我的数据框:

 with open(r'test.txt', 'w') as f:
    df.to_string(f, col_space=10, index=False)

有没有办法在我的代码中添加内容,这样我的导出文件在显示实际数据和列标题之前有几行文本?

【问题讨论】:

    标签: python-3.x pandas dataframe text


    【解决方案1】:

    df.to_string() 被写入文件之前直接写入文件。 W3 Schools 有一个simple walkthrough

    f.write("Whatever your header text looks like(Line 1)\n")
    f.write("Whatever your header text looks like(Line 2)\n")
    

    【讨论】:

      【解决方案2】:

      其实是有的。可以添加属性

      import pandas as pd
      df = pd.DataFrame([])
      df.attrs['my attributes`] = 'this is the content'
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-06-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多