5

I am using if in a conditional statement like the below code. If address is NJ then the value of name column is changed to 'N/A'.

df1.loc[df1.Address.isin(['NJ']), 'name'] = 'N/A'

How do I do the same, if I have 'nested if statements' like below?

# this not code just representing the logic
if address isin ('NJ', 'NY'):
    if name1 isin ('john', 'bob'):
        name1 = 'N/A' 
    if name2 isin ('mayer', 'dylan'):
        name2 = 'N/A'

Can I achieve above logic using df.loc? Or is there any other way to do it?

0

2 Answers 2

4

Separate assignments, as shown by @MartijnPeiters, are a good idea for a small number of conditions.

For a large number of conditions, consider using numpy.select to separate your conditions and choices. This should make your code more readable and easier to maintain.

For example:

import pandas as pd, numpy as np

df = pd.DataFrame({'address': ['NY', 'CA', 'NJ', 'NY', 'WS'],
                   'name1': ['john', 'mayer', 'dylan', 'bob', 'mary'],
                   'name2': ['mayer', 'dylan', 'mayer', 'bob', 'bob']})

address_mask = df['address'].isin(('NJ', 'NY'))

conditions = [address_mask & df['name1'].isin(('john', 'bob')),
              address_mask & df['name2'].isin(('mayer', 'dylan'))]

choices = ['Option 1', 'Option 2']

df['result'] = np.select(conditions, choices)

print(df)

  address  name1  name2    result
0      NY   john  mayer  Option 1
1      CA  mayer  dylan         0
2      NJ  dylan  mayer  Option 2
3      NY    bob    bob  Option 1
4      WS   mary    bob         0
Sign up to request clarification or add additional context in comments.

Comments

3

Use separate assignments. You have different conditions to filter on, you can combine the address and the two name* filters with & (but put parentheses around each test):

df1.loc[(df1.Address.isin(['NJ'])) & (df1.name1 isin ('john', 'bob')), 'name1'] = 'N/A'
df1.loc[(df1.Address.isin(['NJ'])) & (df1.name2 isin ('mayer', 'dylan')), 'name2'] = 'N/A'

You can always store the boolean filters in a variable first:

nj_address = df1.Address.isin(['NJ'])
name1_filter = df1.name1 isin ('john', 'bob')
name2_filter = df1.name2 isin ('mayer', 'dylan')
df1.loc[nj_address & name1_filter, 'name1'] = 'N/A'
df1.loc[nj_address & name2_filter, 'name2'] = 'N/A'

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.