2

I have a Pandas DataFrame with three columns and every string in these columns ends with '\n'

Example:

test\n | abc\n | 123\n

Now, I want to get rid of these '\n' and achieve:

test | abc | 123

I only find solutions where substrings are removed from certain columns, but I want to remove this substring from the entire DataFrame

I would therefore be very happy if someone had a solution to my problem.

Thank you very much in advance for your help!

1 Answer 1

3

Use:

df = df.apply(lambda s: s.str.strip())

To limit to a list of columns:

# cols = ['col1', 'col2']
df[cols] = df[cols].apply(lambda s: s.str.strip())
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you, your approach worked very well! Since I also got some "\n" inside some strings I slightly modified your solution from: df = df.apply(lambda s: s.str.strip()) to: df = df.apply(lambda s: s.str.replace("\n",""))
@RKF yes sure, I thought this was only for the final '\n' ;)
Is it needed to use index = True or something like that? It's not working for me.

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.