简体   繁体   中英

map() function on pandas DataFrame in python does not work as expected

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'

在此处输入图像描述

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) )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM