0

I have one csv file that has 6 columns like date_time, humidity, temp_c etc..

I want to extract month-wise data and find the mean of humidity per month. Note: without using third party lib like pandas numpy etc..only python oops concepts

import csv

with open('path', mode='r') as csv_file:
    csv_reader = csv.DictReader(csv_file)
    for row in csv_reader:
        for key, value in row.items():
            temp[key] = value

2 Answers2

1

Given this example.csv:

date_time,humidity,temp_c
2020 Jan 1, 12, 25
2020 Jan 2, 13, 25
2020 Feb 2, 14, 25
2020 Feb 3, 15, 25

Here is a working solution:

# https://stackoverflow.com/questions/49584924/python-group-dates-by-month
import pandas as pd

#https://stackoverflow.com/questions/52842977/read-csv-to-pandas-retaining-values-as-it-is
df = pd.read_csv("example.csv")
print(df)

#https://stackoverflow.com/questions/55684075/pandas-to-datetime-changes-year-unexpectedly
df['date'] = pd.to_datetime(df['date_time'])
print(df)

#https://stackoverflow.com/questions/23840797/convert-a-column-of-timestamps-into-periods-in-pandas
df['month'] = pd.DatetimeIndex(df['date']).to_period('M')

print(df)
df = df.groupby("month")
print(df)

# https://stackoverflow.com/questions/31037298/pandas-get-column-average-mean
print(df["humidity"].mean())
poleguy
  • 523
  • 7
  • 11
0

Pandas is great for this. The doc is here, and you should be able to find your answer by checking out the doc for functions like read_csv and mean.

This question might also help.

manny
  • 338
  • 1
  • 11