Wboy
Wboy

Reputation: 2552

Proper pandas map syntax with multiple values

I know I'm almost there, but can't figure out the faster syntax for the equivalent of the below code:

def is_evening(df):
    lst = []
    for i in df.index:
        val = df["localized_time"][i]
        if val != 'NA':
            if val.hour >= 17 and val.hour <= 3:
                lst.append(1)
            else:
                lst.append(0)
        else:
            lst.append(-1)
    df["is_evening"] = lst
    return df

If it was just two values it would be easy, but with the additional conditions and stuff, is there a fast way to do this using pandas map?

What I have so far:

mask = [df["localized_time"] != 'NA']
df["is_evening"] = df["is_evening"] = df["localized_time"][mask].apply(lambda x: 1 if (x.hour >= 17 and x.hour <= 23) else 0)
# Doesn't seem to work

Could anyone help me out? Thank you! :)

Upvotes: 0

Views: 619

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477210

Yes there definitely is:

def f(x):
    return int(x.hour >= 17 and x.hour <= 3) if x != 'NA' else -1

df["is_evening"] = df["localized_time"].apply(f)

So here f is a function that maps a single localized_time element to an is_evening element. We can also use a lambda expression, but this will be more ugly:

df["is_evening"] = df["localized_time"].\
    apply(lambda x: int(x.hour >= 17 and x.hour <= 3) if x != 'NA' else -1)

Upvotes: 1

Related Questions