0

Current situation. I don't know if my function is correct and how to "apply" to pd.Series.

Function:

def levels(row):
if row.between(0,3):
    return "basic"
elif row.between(3.01, 8.5):
    return "intermediate"
else:
    return "advanced"

My Series: test_result["Points"] looks:

    1            3.0
Book1            0.0
Maja             1.0
Michal.Faron     0.0
Solutions       10.0
Name: Points, dtype: float64

I have tried:

test_result['LEVEL']=test_result["Points"].apply(levels)

I want at the end additional column: LEVEL with strings based on if criteria within my function

4
  • I think map is a better use for your syntax. Try test_result['LEVEL']=map(levels, est_result["Points"]) Jan 30, 2020 at 17:07
  • Alireza when I use your suggestion it is close and my result is: Points LEVEL 1 3.0 <map object at 0x000001E06D170D90> Book1 0.0 <map object at 0x000001E06D170D90> Maja 1.0 <map object at 0x000001E06D170D90> Michal.Faron 0.0 <map object at 0x000001E06D170D90> Solutions 10.0 <map object at 0x000001E06D170D90>
    – Mishko
    Jan 30, 2020 at 17:11
  • Put a list outside of map as in : list(map(....)) Jan 30, 2020 at 17:11
  • 1
    This is much better done with pd.cut. Right now your elif logic is a bit wonky, for instance 3.001 is included in the else clause though you probably wouldn't want that. Really you should define proper bins with consistent closing.
    – ALollz
    Jan 30, 2020 at 17:17

2 Answers 2

4

It will be quite slow if applied to a large dataset. Would suggest using mask or loc;

df['level'] = 'advanced'
df.loc[3.01 <= df.points < 8.5, 'level'] = 'intermediate'
df.loc[0 <= df.points < 3.01, 'level'] = 'basic'

Should be a lot quicker.

EDIT

Oh, I thought that would work, but it doesn't. Use this instead;

df.loc[(df.points >= 3.01) & (df.points < 8.5), 'level'] = 'intermediate'
df.loc[(df.points >= 0) & (df.points < 3.01), 'level'] = 'basic'
1
  • When I put this into my code i got: ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
    – Mishko
    Jan 30, 2020 at 17:35
0

The problem is that row is a float, and floats do not have between method. If you really want to use it you can convert it back to be a pandas series:

def levels(row):
    if pd.Series([row]).between(0,3)[0]:
        return "basic"
    elif pd.Series([row]).between(3.01, 8.5)[0]:
        return "intermediate"
    else:
        return "advanced"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.