1

I've managed to group a data frame by Datetime month doing this:

df.set_index('Date').groupby(pd.Grouper(freq='M')).sum()

The data looks like this:

           price, debt
2018-4-30, 40.0, 50,0
2018-5-31, 10.0, 0.0
2018-6-30, 30.0, 0.0
2018-7-31, 30.0, 10.0

When I run print(df.index), it gives me this:

DatetimeIndex(['2018-04-30', '2018-05-31', '2018-6-30', '2018-7-31'], dtype='datetime64[ns]', name='Date', freq='M')

Is there a way to match a column by the Month/year in the index? So, if I wanted to get a price in July of 2018, it'll return 30.0. If not, what is the best way to do that? Thank you.

1 Answer 1

1

Use partial string indexing by year and months with item for convert one element Series to scalar:

print(df['2018-07']['price'].item())
30.0

Or use grouping by MS for start of string and select by loc with first day:

df = df.set_index('Date').groupby(pd.Grouper(freq='MS')).sum()
print (df)
            price  debt
Date                   
2018-04-01   40.0  50.0
2018-05-01   10.0   0.0
2018-06-01   30.0   0.0
2018-07-01   30.0  10.0

print(df.loc['2018-07-01', 'price'])
30.0

Another solution is convert datetimes to month period by to_period:

df['Date'] = df['Date'].dt.to_period('M')
df = df.groupby('Date').sum()
print (df)
         price  debt
Date                
2018-04   40.0  50.0
2018-05   10.0   0.0
2018-06   30.0   0.0
2018-07   30.0  10.0

print (df.loc['2018-07', 'price'])
30.0

If use some old version of pandas also working (thanks Alexander ):

df.loc['2018-07', 'price']

but in pandas 0.22.0 get:

KeyError: 'the label [2018-07] is not in the [index]'

4
  • Given that there is only one date per month, just using df.loc['2018-07', 'price'] should work fine, no?
    – Alexander
    Apr 27, 2018 at 7:10
  • @Alexander - with datetimeindex not.
    – jezrael
    Apr 27, 2018 at 7:11
  • @Alexander get KeyError: 'the label [2018-07] is not in the [index]'
    – jezrael
    Apr 27, 2018 at 7:12
  • I'm using an older version of Pandas (0.17.1, don't ask...), and it works fine.
    – Alexander
    Apr 27, 2018 at 7:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.