0

I have a column in a Pandas dataframe that sometimes contains blank rows. I want to use str.strip() to tidy up the rows that contain strings but this gives me the following error when a row is empty:

AttributeError: Can only use .str accessor with string values!

This is the code:

ts_df['Message'] = ts_df['Message'].str.strip()

How do I ignore the blank rows?

0

2 Answers 2

3

str.strip() should be able to handle NaN values if your column contains only strings and NaN. So, it's most probably your column is mixed with other non-string types (e.g. int or float, not string of int or float but really of type int or float).

If you want to clean up the column and maintain only string type values, you can cast it to string by .astype(str). However, NaN will also be casted to string 'nan' when the column is casted to string. Hence, you have to replace NaN by empty string first by .fillna() with empty string before casting to string type, as follows:

ts_df['Message'] = ts_df['Message'].fillna('').astype(str).str.strip()
Sign up to request clarification or add additional context in comments.

Comments

3

May be your column contains null values which resulting the dtype as float64 instead of str. Try converting the column to string first using astype(str)

 ts_df['Message'] = ts_df['Message'].astype(str).str.strip()

1 Comment

Thanks guys. SeaBean, your suggestion seems to have worked.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.