Skip to content Skip to sidebar Skip to footer

How To Shorten My Code With Lambda Statement In Python?

I have trouble with shortening my code with lambda if possible. bp is my data name. My data looks like this: user label 1 b 2 b 3 c I expect to have

Solution 1:

Since True and False evaluate to 1 and 0, respectively, you can simply return the Boolean expression, converted to integer.

def score_to_numeric(x):
    return int((counts['b'] > counts['s']) == \
               (x == 'b'))

It returns 1 iff both expressions have the same Boolean value.


Solution 2:

I don't think you need to use the apply method. Something simple like this should work:

value_counts = bp.Label.value_counts()
bp.Label[bp.Label == 'b'] = 1 if value_counts['b'] > value_counts['s'] else 0
bp.Label[bp.Label == 's'] = 1 if value_counts['s'] > value_counts['b'] else 0

Solution 3:

You could do the following

counts = bp['Label'].value_counts()
t = 1 if counts['b'] > counts['s'] else 0
bp['Y'] = bp['Label'].apply(lambda x: t if x == 'b' else 1 - t)

Post a Comment for "How To Shorten My Code With Lambda Statement In Python?"