Home > other >  How to take a list of second-level column names from a pandas dataframe with multiple indexes
How to take a list of second-level column names from a pandas dataframe with multiple indexes

Time:07-11

Attributes    Close             High              Low             Open  \
Symbols        1.HK   10.HK     1.HK   10.HK     1.HK   10.HK     1.HK   
Date                                                                     
2022-01-04  49.7049  15.862  49.9950  15.862  49.4148  15.728  49.8983   
2022-01-05  50.8170  15.785  51.2038  15.920  49.6082  15.670  50.0434   
2022-01-06  50.8170  15.555  51.0587  15.689  50.1401  15.478  50.9137   
2022-01-07  51.2038  15.708  51.2521  15.747  50.4302  15.536  50.8170   
2022-01-10  52.2675  15.843  52.3159  15.881  51.0587  15.670  51.4939   

Attributes                Volume            
Symbols      10.HK          1.HK     10.HK  
Date                                        
2022-01-04  15.728  3.390678e 06  273315.0  
2022-01-05  15.862  7.322568e 06  387293.0  
2022-01-06  15.689  3.387272e 06  273970.0  
2022-01-07  15.555  6.733935e 06  964852.0  
2022-01-10  15.670  6.098043e 06  386389.0  

How to get list that will contain the columns names from second layer - example ["1.HK","10.HK"]

CodePudding user response:

Like this, you can iterate df.columns and get the column levels as tuples. 1 is the second level. Deduplicate them as a later step if needed.

[col[1] for col in df.columns]

Alternatively, you can also use

(df.columns.get_level_values(1)
 .unique()  # if needed
)

CodePudding user response:

Or

df.loc[:, "Close"].columns.values

if each of the main columns has the same sub-columns

  • Related