简体   繁体   English

CSV文件的输出格式-Python

[英]Output format of csv file - Python

From a csv file having the following format: 来自具有以下格式的csv文件:

Date,Data
01-01-01,111
02-02-02,222
03-03-03,333

I am calculating the monthly average of the values using the following code: 我正在使用以下代码计算值的每月平均值:

data = pd.read_csv("input.csv")
data['Month'] = pd.DatetimeIndex(data.reset_index()['Date']).month
mean_data = data.groupby('Month').mean()

Then I would like to write the outputted monthly values on a new csv file. 然后,我想将输出的每月值写在新的csv文件中。 I am currently using the following lines of code: 我目前正在使用以下代码行:

 with open ("test.csv", "w") as f:
     print(mean_data, file=f)

Unfortunately, this produces a weird output having the following format: 不幸的是,这产生了具有以下格式的奇怪输出:

      Data
Month
1        2
2        3
3        4
4        5

I would like to obtain a real csv output as follow: 我想获得一个真实的csv输出,如下所示:

Month,Data
1,2
2,3
3,4
4,5

Does anyone knows how to achieve that? 有谁知道如何做到这一点?

Instead of using: 而不是使用:

 with open ("test.csv", "w") as f:
    print(mean_data, file=f)

You could try and use: 您可以尝试使用:

import csv

header = ['Month', 'Data']
with open("test.csv", "w") as f:
    writer = csv.writer(f)
    writer.writerow(header)
    writer.writerows(mean_data)

I've tried to recreate your problem and above should provide a solution. 我试图重新创建您的问题,以上应该提供解决方案。

You could use mean_data.to_csv(...) 您可以使用mean_data.to_csv(...)

Here is the documentation: 这里是文档:

Pandas to_csv 熊猫to_csv

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

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