How do I perform analysis on a multi-index column?

So for example following is the piece of data resulted from a group by statement

 MultiIndex(levels=[['sold_at'], ['ACHUTAN', 'AKKI', 'DHRUV', 'DISHA', 'INDER', 'KUNAL', 'MANU']],
               codes=[[0, 0, 0, 0, 0, 0, 0], [0, 1, 2, 3, 4, 5, 6]],
               names=[None, 'owner'])
                 sold_at                                  
    owner        ACHUTAN AKKI DHRUV DISHA INDER KUNAL MANU
    national                                              
    AFGHANISTAN      2.0  1.0   3.0   NaN   NaN   2.0  1.0
    AUSTRALIA        2.0  NaN   3.0   3.0   2.0   1.0  2.0
    BANGLADESH       1.0  1.0   3.0   2.0   NaN   1.0  1.0
    ENGLAND          2.0  3.0   NaN   2.0   2.0   2.0  1.0
    INDIA            2.0  2.0   2.0   2.0   3.0   3.0  1.0
    NEW ZEALAND      NaN  3.0   1.0   NaN   1.0   1.0  3.0
    PAKISTAN         1.0  3.0   1.0   1.0   NaN   1.0  3.0
    SOUTH AFRICA     3.0  1.0   NaN   2.0   3.0   1.0  1.0
    SRI LANKA        NaN  1.0   1.0   1.0   1.0   1.0  2.0
    WEST INDIES      2.0  NaN   1.0   2.0   3.0   2.0  NaN

what if I wanted just national in one column and the count from 'DHRUV and 'DISHA'?

Can you post the code used to generate this?

What do you mean by national in one column and count from
"DHRUV" and "DISHA"

@alvinctk What I mean was I wanted something like

df.loc[:,['DHRUV', 'DISHA']]

this will work:
new_dataframe = df[['DHRUV','DISHA']]

2 Likes

I don’t think that will work @Abdelrahman

            new_df = analysis_sum[['DHRUV', 'DISHA']]
            print(new_df)

            Traceback (most recent call last):
              File "./auction.py", line 48, in <module>
                new_df_dq = analysis_sum[['DHRUV', 'DISHA']]
              File "/usr/local/lib/python3.7/site-packages/pandas/core/frame.py", line 2934, in __getitem__
                raise_missing=True)
              File "/usr/local/lib/python3.7/site-packages/pandas/core/indexing.py", line 1354, in _convert_to_indexer
                return self._get_listlike_indexer(obj, axis, **kwargs)[1]
              File "/usr/local/lib/python3.7/site-packages/pandas/core/indexing.py", line 1142, in _get_listlike_indexer
                kind=self.name)
              File "/usr/local/lib/python3.7/site-packages/pandas/core/indexes/multi.py", line 2136, in _convert_listlike_indexer
                raise KeyError('%s not in index' % keyarr[mask])
            KeyError: "['DHRUV' 'DISHA'] not in index"

What actually worked for me was 

new_df = analysis_sum['sold_at'][['DHRUV', 'DISHA']]
print(new_df)

owner  DHRUV  DISHA
0        5.5    NaN
1       22.5    2.5
2        5.0    1.0
3        NaN   16.0
4        3.5   25.0
5       10.0    NaN
6        0.5    0.5
7        NaN    6.5
8        0.5    0.5
9        4.5    7.5
1 Like