Python pandas - build subset based on column names

Here is my multi-index frame:

                             A                    B
                             Net   Upper   Lower  Mid  Zsore
Answer option                                                
More than once a day          0%   0.22%  -0.12%   2    65 
Once a day                    0%   0.32%  -0.19%   3    45
Several times a week          2%   2.45%   1.10%   4    78
Once a week                   1%   1.63%  -0.40%   6    65

      

I would like to build a subset of COLUMN NAME on a second level (nothing fancy) that only keeps the following columns: "Net, Upper, Zscore"

                             Net   Upper  Zsore
Answer option                                               
More than once a day          0%   0.22%    65 
Once a day                    0%   0.32%    45
Several times a week          2%   2.45%    78
Once a week                   1%   1.63%    65

      

My unsuccessful attempt to pull this out, I guess it fails because I don't know how to account for 2 levels of columns?

df = df[[u'Net',u'Upper',u'Zsore']]

      

+3


source to share


1 answer


May be:



>>> j = df.columns.get_level_values(1).isin(['Net', 'Upper', 'Zsore'])
>>> df.loc[:,j]
                       A             B
                     Net  Upper  Zsore
Answer option                         
More than once a day  0%  0.22%     65
Once a day            0%  0.32%     45
Several times a week  2%  2.45%     78
Once a week           1%  1.63%     65

      

+2


source







All Articles