pankaj
pankaj

Reputation: 460

Or logic not working when there are NaN values using Python

I have dataframe (df) like below

address1            address2            Subject
NaN                 [email protected]   Invoice 3
NaN                 NaN                 Invoice 4
[email protected]     [email protected]     Invoice 5

My logic is as below

  1. If value is present for address1 and address2 is present then to_address value should be Address1

  2. If no values are present are in Address 1 and Address 2 or both are NaN then "david@gmailcom" should be taken

  3. If address1 value is not prsent or NaN and address2 value is present then this should be taken.

But my or-logic code doesnt work as required. What is the mistake I am making.

My code:

for i, row in df.iterrows():
    subject  = row["Subject"]
    to_address = row['address1'] or row['address2'] or "david@gmailcom"

Upvotes: 0

Views: 114

Answers (2)

Dorian
Dorian

Reputation: 1488

First, you should simplify your logic a bit (the explanation is quite confusing for me).

Second, what type is NaN? I assumed it is float('nan'), but if it is just string NaN then you need to change float('nan') to NaN

As far as I understood, it is like this:

for i, row in df.iterrows():
    subject  = row["Subject"]
    if row['address1'] == float('nan'):
        to_address = row['address1']
    elif row['address2'] == float('nan'):
        to_address = row['address2']
    else:
        to_address = "david@gmailcom"

So if the first address is NaN, then the second one is checked. If that one is NaN as well then the default is chosen.

Upvotes: 0

Let's try
Let's try

Reputation: 1058

Try to do it with a lambda function:

df = pd.DataFrame([[float("nan"),"[email protected]","Invoice 3"],[float("nan"),float("nan"),"Invoice 4"],
                   ["[email protected]","[email protected]","Invoice 5"]], columns = ["address1","address2","Subject"])
df["case"] = df.apply(lambda x: x["address1"] if not pd.isna(x["address1"]) \
                                else x['address2'] if not pd.isna(x["address2"]) \
                                else "david@gmailcom", axis = 1)
df

    address1        address2            Subject     case
0   NaN             [email protected]   Invoice 3   [email protected]
1   NaN             NaN                 Invoice 4   david@gmailcom
2   [email protected] [email protected]     Invoice 5   [email protected]

Upvotes: 1

Related Questions