3

I have a dataframe with multiple columns. I want to look at one column and if any of the strings in the column contain @, I want to replace them with another string. How would I go about doing this?

3 Answers 3

7

A dataframe in pandas is composed of columns which are series - Panda docs link

I'm going to use regex, because it's useful and everyone needs practice, myself included! Panda docs for text manipulation

Note the str.replace. The regex string you want is this (it worked for me): '.*@+.*' which says "any character (.) zero or more times (*), followed by an @ 1 or more times (+) followed by any character (.) zero or more times (*)

df['column'] = df['column'].str.replace('.*@+.*', 'replacement')

Should work, where 'replacement' is whatever string you want to put in.

Sign up to request clarification or add additional context in comments.

Comments

3

My suggestion:

df['col'] = ['new string' if '@' in x else x for x in df['col']]

not sure which is faster.

Comments

3

Assuming you called your dataframe df, you can do:

pd.DataFrame(map(lambda col: map(lambda x: 'anotherString' if '@' in x else x, df[col]), df.columns)).transpose()

3 Comments

If you're interested in a sublist of specific columns, just put them instead of df.columns
This replaces the @ value with the String I input, Im looking to replace the entire string with a new value if the current string contains @ sorry if I didnt specify
OK, I modified the answer accordingly

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.