Explore Courses Blog Tutorials Interview Questions
0 votes
in Python by (45.3k points)

This is my code:

df = pd.DataFrame({'First':[1,2,3,4],'Second':[1,2,3,'string'],'Third':[1,2,3,4],'Fourth':['string','lava','cake','Volcano']})

columns = df.applymap(np.isreal).all()



True_columns = []

False_columns = []

The output is:

<class 'pandas.core.series.Series'>

First      True

Second    False

Third      True

Fourth    False

dtype: bool

I need to save all the columns with TRUE (First, Third) in True_columns list and all the FALSE (Second, Fourth) in False_columns list. I am learning pandas. Could anyone help me on how to achieve this requirement?

Thanks in advance.

1 Answer

0 votes
by (16.8k points)

Filter by boolean indexing and for False_columns invert boolean mask by ~:

True_columns  = df.columns[columns].tolist()

print (True_columns)

['First', 'Third']

False_columns = df.columns[~columns].tolist()

print (False_columns)

['Second', 'Fourth']

Or try like this:

True_columns = columns.index[columns].tolist()

False_columns = columns.index[~columns].tolist()


True_columns = columns[columns].index.tolist()

False_columns = columns[~columns].index.tolist()

Another way to try this is to use DataFrame.select_dtypes:

True_columns = df.select_dtypes(np.number).columns.tolist()

print (True_columns)

['First', 'Third']

False_columns = df.select_dtypes('object').columns.tolist()

print (False_columns)

['Second', 'Fourth']

Browse Categories