get list of pandas dataframe columns based on data type

前端 未结 12 1406
后悔当初
后悔当初 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:54

    If you want a list of columns of a certain type, you can use groupby:

    >>> df = pd.DataFrame([[1, 2.3456, 'c', 'd', 78]], columns=list("ABCDE"))
    >>> df
       A       B  C  D   E
    0  1  2.3456  c  d  78
    
    [1 rows x 5 columns]
    >>> df.dtypes
    A      int64
    B    float64
    C     object
    D     object
    E      int64
    dtype: object
    >>> g = df.columns.to_series().groupby(df.dtypes).groups
    >>> g
    {dtype('int64'): ['A', 'E'], dtype('float64'): ['B'], dtype('O'): ['C', 'D']}
    >>> {k.name: v for k, v in g.items()}
    {'object': ['C', 'D'], 'int64': ['A', 'E'], 'float64': ['B']}
    

提交回复
热议问题