Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python pandas - build subset based on column names

Here is my multi-index dataframe:

                             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 by COLUMN NAME on the second level (nothing fancy) which keeps the following columns only "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 failed attempt to pull this off, I guess it fails because I don't know how to account for the 2 levels of columns?

df = df[[u'Net',u'Upper',u'Zsore']]
like image 893
Boosted_d16 Avatar asked Jun 11 '26 06:06

Boosted_d16


1 Answers

Maybe:

>>> 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
like image 73
behzad.nouri Avatar answered Jun 13 '26 00:06

behzad.nouri



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!