get list of pandas dataframe columns based on data type

前端 未结 12 1368
后悔当初
后悔当初 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']   
    
    0 讨论(0)
  • 2020-12-07 07:48
    list(df.select_dtypes(['object']).columns)
    

    This should do the trick

    0 讨论(0)
  • 2020-12-07 07:53

    As of pandas v0.14.1, you can utilize select_dtypes() to select columns by dtype

    In [2]: df = pd.DataFrame({'NAME': list('abcdef'),
        'On_Time': [True, False] * 3,
        'On_Budget': [False, True] * 3})
    
    In [3]: df.select_dtypes(include=['bool'])
    Out[3]:
      On_Budget On_Time
    0     False    True
    1      True   False
    2     False    True
    3      True   False
    4     False    True
    5      True   False
    
    In [4]: mylist = list(df.select_dtypes(include=['bool']).columns)
    
    In [5]: mylist
    Out[5]: ['On_Budget', 'On_Time']
    
    0 讨论(0)
  • 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']}
    
    0 讨论(0)
  • 2020-12-07 07:55

    use df.info(verbose=True) where df is a pandas datafarme, by default verbose=False

    0 讨论(0)
  • 2020-12-07 07:55

    for yoshiserry;

    def col_types(x,pd):
        dtypes=x.dtypes
        dtypes_col=dtypes.index
        dtypes_type=dtypes.value
        column_types=dict(zip(dtypes_col,dtypes_type))
        return column_types
    
    0 讨论(0)
提交回复
热议问题