Using Apply in Pandas Lambda functions with multiple if statements

后端 未结 4 1581
一生所求
一生所求 2021-02-09 12:08

I\'m trying to infer a classification according to the size of a person in a dataframe like this one:

      Size
1     80000
2     8000000
3     8000000000
...
<         


        
4条回答
  •  既然无缘
    2021-02-09 12:42

    Here is a small example that you can build upon:

    Basically, lambda x: x.. is the short one-liner of a function. What apply really asks for is a function which you can easily recreate yourself.

    import pandas as pd
    
    # Recreate the dataframe
    data = dict(Size=[80000,8000000,800000000])
    df = pd.DataFrame(data)
    
    # Create a function that returns desired values
    # You only need to check upper bound as the next elif-statement will catch the value
    def func(x):
        if x < 1e6:
            return "<1m"
        elif x < 1e7:
            return "1-10m"
        elif x < 5e7:
            return "10-50m"
        else:
            return 'N/A'
        # Add elif statements....
    
    df['Classification'] = df['Size'].apply(func)
    
    print(df)
    

    Returns:

            Size Classification
    0      80000            <1m
    1    8000000          1-10m
    2  800000000            N/A
    

提交回复
热议问题