【问题标题】:How to filter and find out all the columns of a certain data type in pandas dataframe?如何过滤并找出熊猫数据框中某种数据类型的所有列?
【发布时间】:2021-06-15 07:05:51
【问题描述】:

让我有一个数据框df

 Name     Age       Job
 
 Rick     24      Worker
 Max      20      Worker
 Sam      48      Driver
 
 Expected output:  
                  Name
                  Job

现在,我想打印出那些具有 object 类型数据的列(名称)。
这是我的尝试:

for column in df:
    if df.dtypes(column) == 'object':
        print(column)

但我收到一个错误,即: " 如果 df.dtypes(column) == 'object': 类型错误:“系列”对象不可调用“

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    你可以使用df.select_dtypes如下:

    df.select_dtypes('object').columns.to_list()
    

    输出:

    ['Name', 'Job']
    

    或者:

    for column in df:
        if df[column].dtype == 'object':
            print(column)
    
    

    【讨论】:

      【解决方案2】:

      您可以使用列表推导:

      [x for x in df.columns if df[x].dtype == object]
      

      输出:

      ['Name', 'Job']
      

      【讨论】:

        【解决方案3】:

        试试

        df.columns[df.dtypes == object].to_list()
        

        给了

        >> ['Name', 'Job']
        

        【讨论】:

          【解决方案4】:

          错误是由 for 循环引起的。试试:

          for column in df.columns:
              if type(column) == 'object':
                  print(column)
          

          【讨论】:

            【解决方案5】:

            这是一个尝试:

            代码:

            df.dtypes[df.dtypes == 'object'].index.values
            

            打印:

            array(['Name', 'Job'], dtype=object)
            

            用于打印列本身:

            [print(val) for val in df.dtypes[df.dtypes == 'object'].index]
            Name
            Job
            

            【讨论】:

              【解决方案6】:
              import numpy as np
              # Get columns whose data type is object
              filteredColumns = df.dtypes[df.dtypes == np.object]
              # List of columns whose data type is object
              listOfColumnNames = list(filteredColumns.index)
              print(listOfColumnNames)
              

              输出:

              ['姓名', '工作']

              【讨论】:

                【解决方案7】:

                另一种方法:

                [print(col) for col in df.select_dtypes(include = object).columns]
                Name
                Job
                

                【讨论】:

                  猜你喜欢
                  • 2016-08-02
                  • 2017-02-05
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 2018-07-13
                  • 2021-12-01
                  • 1970-01-01
                  • 1970-01-01
                  相关资源
                  最近更新 更多