GeorgeWilson
GeorgeWilson

Reputation: 592

Index pandas series by an hour

In my code I am currently doing the following kind of operation with Pandas:

ser = oldser.dropna().copy()
for i in range(24):
    ind = ser.groupby(ser.index.hour).get_group(i).index
    ser[ind]=something

This code copies a series, and then for takes each hour separately and does something to it. This seems very messy though - any ways to nicely clean it up?

What I really want, is something analogous to

series['2011']

which gets all data from 2011, but instead

series['2pm'] 

getting all data at 2pm.

Upvotes: 1

Views: 49

Answers (1)

Andy Hayden
Andy Hayden

Reputation: 375515

Certainly you want to do the groupby operation once, a slight refactor:

g = ser.groupby(ser.index.hour)
for i, ind in g.indices:
    ser.iloc[ind] = something

But most likely you can do a transform or apply (depending on what something is):

g.transform(something)
g.apply(something)

Upvotes: 1

Related Questions