get list of pandas dataframe columns based on data type

前端 未结 12 1390
后悔当初
后悔当初 2020-12-07 07:37

If I have a dataframe with the following columns:

1. NAME                                     object
2. On_Time                                      object
         


        
12条回答
  •  情歌与酒
    2020-12-07 07:43

    The most direct way to get a list of columns of certain dtype e.g. 'object':

    df.select_dtypes(include='object').columns
    

    For example:

    >>df = pd.DataFrame([[1, 2.3456, 'c', 'd', 78]], columns=list("ABCDE"))
    >>df.dtypes
    
    A      int64
    B    float64
    C     object
    D     object
    E      int64
    dtype: object
    

    To get all 'object' dtype columns:

    >>df.select_dtypes(include='object').columns
    
    Index(['C', 'D'], dtype='object')
    

    For just the list:

    >>list(df.select_dtypes(include='object').columns)
    
    ['C', 'D']   
    

提交回复
热议问题