Mar
Mar

Reputation: 411

how to group data of 4 years seasonly using pandas

i have a csv file containing 4 years of data, i need to group my data per season over the 4 years : here's a look of my data :

timestamp,heure,lat,lon,impact,type
2006-01-01 00:00:00,13:58:43,33.837,-9.205,10.3,1
2006-01-02 00:00:00,00:07:28,34.5293,-10.2384,17.7,1
2007-02-01 00:00:00,23:01:03,35.0617,-1.435,-17.1,2
2007-02-02 00:00:00,01:14:29,36.5685,0.9043,36.8,1
2008-01-01 00:00:00,05:03:51,34.1919,-12.5061,-48.9,1
2008-01-02 00:00:00,05:03:51,34.1919,-12.5061,-48.9,1
....
2011-12-31 00:00:00,05:03:51,34.1919,-12.5061,-48.9,1

and here's my desired output :

winter     (the mean value of impacts)
summer     (the mean value of impacts)
autumn      ....
spring      .....

so i am expecting 4 rows summarizing all month in 4 seasons . i started as below :

data['impact'] = data['impact'].abs()
yearly = data.groupby(data.index.month)['impact'].mean()

any ideas ??

Upvotes: 1

Views: 260

Answers (2)

steboc
steboc

Reputation: 1181

With exact dates

import pandas as pd
spring = range(80, 172)
summer = range(172, 264)
fall = range(264, 355)

def season(x):
    if x in spring:
        return 'Spring'
    if x in summer:
        return 'Summer'
    if x in fall:
        return 'Fall'
    else :
        return 'Winter'

df = pd.DataFrame({'_date' :pd.date_range(start=pd.datetime(2016,1,1), end=pd.datetime(2016,12,31), freq='D'),'impact' : range(0,366)})    

df['SEASON'] = df['_date'].dt.dayofyear.apply(lambda x : season(x))
df.groupby('SEASON')['impact'].mean()

Upvotes: 1

piRSquared
piRSquared

Reputation: 294358

With crude months... Assumes the timestamps are in the index.

mlist = [[12, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11]]
slist = ['winter', 'spring', 'summer', 'autum']
sdict = {k: v for v, ks in zip(slist, mlist) for k in ks}

df.groupby(df.index.month.map(sdict.get)).impact.mean()

Setup

import pandas as pd
from io import StringIO

txt = """timestamp,heure,lat,lon,impact,type
2006-01-01 00:00:00,13:58:43,33.837,-9.205,10.3,1
2006-01-02 00:00:00,00:07:28,34.5293,-10.2384,17.7,1
2007-02-01 00:00:00,23:01:03,35.0617,-1.435,-17.1,2
2007-02-02 00:00:00,01:14:29,36.5685,0.9043,36.8,1
2008-01-01 00:00:00,05:03:51,34.1919,-12.5061,-48.9,1
2008-01-02 00:00:00,05:03:51,34.1919,-12.5061,-48.9,1
2011-12-31 00:00:00,05:03:51,34.1919,-12.5061,-48.9,1
"""

df = pd.read_csv(StringIO(txt), parse_dates=[0], index_col=0)

Upvotes: 2

Related Questions