2

I have a Dataframe (series) 'df' that looks like the following:

Name
A1001
A1002
B1001
C1001
A1003
B1002
B1003
C1002
D1001
D1002

I want to create a new column called Company which should read 'Alpha' if text starts with 'A', 'Bravo' if text starts with 'B' and 'Others' if text starts with anything else.

I tried:

df['Company'] = 'Alpha' if df.Name.str.startswith('A') else 'Other'

But it gave me an error:

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

Expected Output:

Name     Company
A1001    Alpha
A1002    Alpha
B1001    Bravo
C1001    Other
A1003    Alpha
B1002    Bravo
B1003    Bravo
C1002    Other
D1001    Other
D1002    Other

How can it be done?

2 Answers 2

3

Use numpy.select with Series.str.startswith:

df['Company'] = np.select([df.Name.str.startswith('A'), 
                           df.Name.str.startswith('B')], 
                           ['Alpha', 'Bravo'], 
                           default='Other')
print (df)
    Name Company
0  A1001   Alpha
1  A1002   Alpha
2  B1001   Bravo
3  C1001   Other
4  A1003   Alpha
5  B1002   Bravo
6  B1003   Bravo
7  C1002   Other
8  D1001   Other
9  D1002   Other
Sign up to request clarification or add additional context in comments.

1 Comment

It' working, but the values are not matching. Some of the As are assigned 'Other'.
2

Use np.select to create multi-conditional column:

letter = df['Name'].str[0]
df['Company'] = np.select([letter.eq('A'), letter.eq('B')], ['Alpha', 'Bravo'], default='Other')

    Name Company
0  A1001   Alpha
1  A1002   Alpha
2  B1001   Bravo
3  C1001   Other
4  A1003   Alpha
5  B1002   Bravo
6  B1003   Bravo
7  C1002   Other
8  D1001   Other
9  D1002   Other

Same approach, but now we use a more "self explaining" code:

letter = df['Name'].str[0]
conditions = [letter.eq('A'), letter.eq('B')]
choices = ['Alpha', 'Bravo']

df['Company'] = np.select(conditions, choices, default='Other')

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.