Reputation: 531
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?
Upvotes: 0
Views: 49
Reputation: 56
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.
Upvotes: 2