导出时在列标题之前向python数据帧添加描述



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

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

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

有没有一种方法可以将内容添加到我的代码中,使我导出的文件在显示实际数据和列标题之前有几行文本?

只需在df.to_string()写入文件之前直接写入文件。W3学校有一个简单的演练。

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

实际上有。您可以添加属性

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

最新更新