简体   繁体   中英

iterate through each index item in level=1 in multi-index pandas

I have the following data frame:

import pandas as pd
import datetime as dt
from dateutil.rrule import rrule, MONTHLY

df = pd.DataFrame({
'value' : [4,2,5,6,7,8,6,5,4,1,2,4],
'date': fread_year_month(dt.datetime(2015, 1, 1),dt.datetime(2015, 12, 1)),
'stock': ['amzn']*12
},columns=[
'value', 'date', 'stock'] )

df2 = pd.DataFrame({
'value' : [1]*11,
'date': fread_year_month(dt.datetime(2015, 1, 1),dt.datetime(2015, 11, 1)),
'stock': ['msft']*11
},columns=[
'value', 'date', 'stock'] )

df = df.append(df2)

df.set_index(['stock', 'date'], inplace=True)

def fread_year_month(strt_dt, end_dt):
    dates = [dt for dt in rrule(MONTHLY, dtstart=strt_dt, until=end_dt)]
    return dates

I want to insert a column into this data frame that has the number of days in the year-month associated with the corresponding index level=1.

I'm not sure how to iterate through each index value in level=1.

If I can figure out how to iterate through each item in level=1 then I can simply do the following:

calendar.monthrange(x.year, x.month)[1]

is that what you want?

In [89]: df['days'] = df.index.get_level_values('date').days_in_month

In [90]: df
Out[90]:
                  value  days
stock date
amzn  2015-01-01      4    31
      2015-02-01      2    28
      2015-03-01      5    31
      2015-04-01      6    30
      2015-05-01      7    31
      2015-06-01      8    30
      2015-07-01      6    31
      2015-08-01      5    31
      2015-09-01      4    30
      2015-10-01      1    31
      2015-11-01      2    30
      2015-12-01      4    31
msft  2015-01-01      1    31
      2015-02-01      1    28
      2015-03-01      1    31
      2015-04-01      1    30
      2015-05-01      1    31
      2015-06-01      1    30
      2015-07-01      1    31
      2015-08-01      1    31
      2015-09-01      1    30
      2015-10-01      1    31
      2015-11-01      1    30

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM