Linked Questions

Popular Questions

How to get the dataframe with all rows after grouping?

Asked by At

I have a Dataframe:

df

    Date   Close    Open 
0 2012-01-02  348.36  342.19 
1 2012-01-03  355.23  350.24 
2 2012-01-04  354.00  352.84 
3 2012-01-05  352.23  352.12 
4 2012-01-06  351.24  351.97 

The df has a 14000 rows.

I want to groupby year and month and get a multiindex dataframe.

df['Date'] = pd.to_datetime(df['Date']) 
# df.set_index('Date',inplace=True,drop=True)
df1 = df.groupby([df.Date.dt.year.rename('year'),df.Date.dt.month.rename('month')]).values 

I have tried .values .count(doesn't give my expected output).

expected output:

 df1

year   month Date        Close    Open 
2012   1     2012-01-02  348.36  342.19 
             2012-01-03  355.23  350.24 
             2012-01-04  354.00  352.84 
             2012-01-05  352.23  352.12 
             2012-01-06  351.24  351.97 

Related Questions