0

I tried the following code and worked on it for a long time to correct it. But I do not know what I am doing wrong.

    def hiLow(x):
    if x > 10:
        print(x, 'is greater than 10')
        df['High/Low'] = 'High'
    else:
        print(x, 'is less than 10' )
        df['High/Low'] = 'Low'

df['total'].map(hiLow)

I expected it will add 'High' in the second and third rows of the 'High/Low' column.

When I replaced df['High/Low'] = 'High' and df['High/Low'] = 'Low' with df['High/Low'] = x it prints 15 for all rows.

In the image,

  1. This output is correct
  2. Why is this all returned 'None'
  3. Why is this showing 'object' when at point 4 it is showing as 'int64'

enter image description here

1
  • The problem is that df['High/Low'] = 'Low' replaces the entire column High/Low with 'Low' (the same for df['High/Low'] = 'High') and then the functions returns None (therefore it produces a Series of Nones as you see). You want to return a single value (return 'Low'), not mutating directly the column of df inside the function. Commented May 29, 2022 at 20:13

1 Answer 1

1
def hiLow(x):
    if x > 10:
        print(x, 'is greater than 10')
        str_answer = 'High'
    else:
        print(x, 'is less than 10' )
        str_answer = 'Low'

    return str_answer

df['High/Low'] =  df['total'].apply(lambda x: hiLow(x) )
Sign up to request clarification or add additional context in comments.

1 Comment

using lambda in .apply(lambda x: hiLow(x) ) is redundant, you can and should simply do .apply(hiLow)

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.