How can I reset the first level from a multi-level column by chaining?

How can I remove the first level from a column with multiple levels?

For data frame:

tmp.head(1000).groupby(['user_id', 'aisle_id']).agg({'aisle_id': ['count']})

gives

                 aisle_id
                    count
user_id aisle_id         
382     38              1
        84              2
        115             1
3107    43              1
3321    37              1
        69              2

I want to leave aisle_idin my columns. How can I do this by hooking up commands without having to start another statement?

+4
source share
3 answers

Change the groupby statement.

tmp.head(1000).groupby(['user_id', 'aisle_id'])['aisle_id'].agg(['count'])
+3
source

You can quickly access the first level of multiindex columns using the dot operator. Similar to how you will access columns with an index of the same level.

just add .aisle_idto the end. Or equivalently['aisle_id']

tmp.head(1000).groupby(['user_id', 'aisle_id']).agg({'aisle_id': ['count']}) \
    .aisle_id

                  count
user_id aisle_id       
381     38            1
382     84            2
        115           1
3107    43            1
3321    37            1
        69            2

Reply to comment

@displayname df.aisle_id df.xs('aisle_id'). , , aisle_id. , , , . , , , , aisle_id df.aisle_id. ScottBoston , , , aisle_id.

+2

reset_index 0 True.

tmp.head(1000).groupby(['user_id', 'aisle_id']) \
    .agg({'aisle_id': ['count']}).T.reset_index(level=0, drop=True).T
+1

Source: https://habr.com/ru/post/1678515/


All Articles