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

Time:01-27

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]

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?

CodePudding user response:

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()
  •  Tags:  
  • Related