简体   繁体   English

如何在 1 个 CSV 文件中组合文本和 pandas dataframe

[英]How to combine text and pandas dataframe in 1 CSV file

I am new to pandas and wondering if it is possible to combine text and pandas dataframe in a single csv file.我是 pandas 的新手,想知道是否可以将文本和 pandas dataframe 合并到一个 Z6287CB19675FFE824BAF37 文件中

I can write the dataframe to a csv file without problem, but I would like to put some description above the dataframe to describe when did I collect the data.我可以毫无问题地将 dataframe 写入 csv 文件,但我想在 dataframe 上方添加一些描述以描述我何时收集数据。 Please see the attachment about what I would like to achieve.请参阅附件,了解我想要实现的目标。

Thank you in advance.先感谢您。 在此处输入图像描述

Thank you for David's post.谢谢大卫的帖子。 I think the "encoding='ISO-8859-1' is the key. What I did is put the description in the csv file first, run the script again, it added the dataframe underneath the description. Here is the code我认为“encoding='ISO-8859-1'是关键。我所做的是将描述放在csv文件中,再次运行脚本,它在描述下方添加了dataframe。这是代码

pd.DataFrame.from_dict(dateDir, orient='index').to_csv('test.csv', encoding='ISO-8859-1',mode='a') pd.DataFrame.from_dict(dateDir, orient='index').to_csv('test.csv', encoding='ISO-8859-1',mode='a')

You really answered you own question你真的回答了你自己的问题

  1. get CSV into string将 CSV 转换为字符串
  2. use an f-string to modify it使用 f-string 来修改它
  3. save it as CSV保存为 CSV
import pandas as pd
from datetime import datetime
df = pd.DataFrame([[i for i in range(0,10)] for j in range(0,10)], columns=[chr(97+i) for i in range(0,10)])
fname = "file.csv"
data = df.to_csv(index=False)
data = f'''Date of month: {datetime.now().month}
From Date: {str(datetime(2020,7,1))}
To Date: {str(datetime(2020,7,30))}


{data}'''
with open(fname, "w") as f:
    f.write(data)
print(data)

output output

Date of month: 7
From Date: 2020-07-01 00:00:00
To Date: 2020-07-30 00:00:00


a,b,c,d,e,f,g,h,i,j
0,1,2,3,4,5,6,7,8,9
0,1,2,3,4,5,6,7,8,9
0,1,2,3,4,5,6,7,8,9
0,1,2,3,4,5,6,7,8,9
0,1,2,3,4,5,6,7,8,9
0,1,2,3,4,5,6,7,8,9
0,1,2,3,4,5,6,7,8,9
0,1,2,3,4,5,6,7,8,9
0,1,2,3,4,5,6,7,8,9
0,1,2,3,4,5,6,7,8,9

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM