Home > Back-end >  check if multiple columns are object type
check if multiple columns are object type

Time:05-26

I'm importing an Excel file and when I check the datatype of the pandas series some are object and others are int64.

I want to find out if any of the columns passed are of object type.

When I run:

if df['dim_weight'].dtype == object or df['dim_length'].dtype == object or df['dim_height'].dtype == object:

and some of the columns are not an object this works as expected but when I do the inverse:

if not df['dim_weight'].dtype == object or not df['dim_length'].dtype == object or not df['dim_height'].dtype == object:

the check fails. Is there a more efficient way to check for this in Pandas? I ultimately want to check if any of the columns are not a string. Any guidance is greatly appreciated.

CodePudding user response:

Generally in the logic theory, the opposite of (A or B) is (not A) and (not B), not (not A) or (not B).

CodePudding user response:

You can use the attribute dtypes of dataframe to get a series containing the datatypes of all columns, then compare the series with inte64 and reduce with all to create a boolean condition:

if df.dtypes.eq('int64').all():
    # Execute the statements when condition is True
  • Related