Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

pandas

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 "

like image 298
Sunjaree Avatar asked Oct 21 '25 15:10

Sunjaree


2 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)

like image 87
SeaBean Avatar answered Oct 23 '25 04:10

SeaBean


You can use list comprehension:

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

Output:

['Name', 'Job']
like image 20
Arkadiusz Avatar answered Oct 23 '25 04:10

Arkadiusz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!