Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Drop all rows that contain any string from a dataframe in Pandas

I have a dataframe that contains strings in columns that should be only floats. I saw several solutions on how to drop a row with a specific string or parts of it from an individual column.

So for an individual column I suppose one could do it like this

new_df = df[df['Column'].dtypes != object]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

But this

new_df = df[df.dtypes != object]

did not work. One could iterate over all columns via a loop, but is there a way to drop the strings for all columns at once?

>Solution :

Use DataFrame.select_dtypes:

#excluding object columns
new_df = df.select_dtypes(exclude=object)

#only floats columns
new_df = df.select_dtypes(include=float)

#only numeric columns
new_df = df.select_dtypes(include=np.number)

EDIT:

new_df = df.apply(pd.to_numeric, errors='coerce').dropna()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading