0

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?

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

You could use mean_data.to_csv(...)

Here is the documentation:

Pandas to_csv

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.