简体   繁体   中英

Output format of csv file - Python

From a csv file having the following format:

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. 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:

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(...)

Here is the documentation:

Pandas to_csv

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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