0

I am trying to work with Pandas on some data problems and have come to a point where I am writing code like this:

groups.segment = groups.topic.map(lambda x: 'friends' if 'friend' in str(x) else x)
groups.segment = groups.topic.map(lambda x: 'friends' if 'bro' in str(x) else x)
groups.segment = groups.topic.map(lambda x: 'friends' if 'girls' in str(x) else x)

I would like to write it in a more concise way way where I don't have to have a bunch of copy and paste code. A little bit new to python so not sure how to make it better. Any help appreciated.

Something along the lines of:

groups.segment = groups.segment.map(lambda x: 'friends' if 'bro' or 'girls' or 'friend' in str(x) else x)

Is there a way to do this ?

Thanks for any help !

1
  • 1
    Look into the any built-in function. Commented Nov 18, 2014 at 23:24

3 Answers 3

5

It's probably better not to use lambda here:

def mapper(x)
    if any(y in str(x) for y in ('friend', 'bro', 'girls')):
        return 'friends'
    return x

groups.segment = groups.topic.map(mapper)

You can use any here which returns True when at least one of the passed values is True.

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

Comments

1
lambda x: 'friends' if 'bro' in str(x) or 'girls' in str(x) or 'friend' in str(x) else x

Comments

1

You can avoid map and lambda altogether and use isin(), which ends up working more like the typical Python idiom of if item in ['a', 'b', 'c']:

import pandas as pd

df = pd.DataFrame({'relationship': ['friends', 'friend', 'bro', 'girls']})
df
Out[3]: 
  relationship
0      friends
1       friend
2          bro
3        girls

is_synonym = df.relationship.isin(['friend', 'bro', 'girls'])
df['relationship2'] = df['relationship'].copy()
df.loc[is_synonym, 'relationship2'] = 'friends'
df
Out[15]: 
  relationship relationship2
0      friends       friends
1       friend       friends
2          bro       friends
3        girls       friends

Comments

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.