How to filter and find out all the columns of a certain data type in pandas dataframe?

Viewed 1381

Let I've a dataframe df

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

Now, I want to print out those column(name) which has object type data.
Here, Is my attempt:

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

But I'm getting an error which is: " if df.dtypes(column) == 'object': TypeError: 'Series' object is not callable "

7 Answers

You can use df.select_dtypes as follows:

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

Output:

['Name', 'Job']

Or:

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

You can use list comprehension:

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

Output:

['Name', 'Job']

Try

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

which gives

>> ['Name', 'Job']

The error is caused by the for loop. Try:

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

Here is a try:

code:

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

Prints:

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

For printing out the columns itself:

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

Another approach:

[print(col) for col in df.select_dtypes(include = object).columns]
Name
Job
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)

Output:

['Name', 'Job']

Related