在Pandas中使用Apply Lambda函数具有多个if语句

abu*_*nte 4 python lambda if-statement apply pandas

我试图根据像这样的数据框中的人的大小来推断分类:

      Size
1     80000
2     8000000
3     8000000000
...
Run Code Online (Sandbox Code Playgroud)

我希望它看起来像这样:

      Size        Classification
1     80000       <1m
2     8000000     1-10m
3     8000000000  >1bi
...
Run Code Online (Sandbox Code Playgroud)

我理解理想的过程是应用这样的lambda函数:

df['Classification']=df['Size'].apply(lambda x: "<1m" if x<1000000 else "1-10m" if 1000000<x<10000000 else ...)
Run Code Online (Sandbox Code Playgroud)

我检查了一些关于lambda函数中多个ifs的帖子,这里是一个示例链接,但是这个synthax在多个ifs语句中由于某种原因不适合我,但是它在单个if条件下工作.

所以我尝试了这个"非常优雅"的解决方案:

df['Classification']=df['Size'].apply(lambda x: "<1m" if x<1000000 else pass)
df['Classification']=df['Size'].apply(lambda x: "1-10m" if 1000000 < x < 10000000 else pass)
df['Classification']=df['Size'].apply(lambda x: "10-50m" if 10000000 < x < 50000000 else pass)
df['Classification']=df['Size'].apply(lambda x: "50-100m" if 50000000 < x < 100000000 else pass)
df['Classification']=df['Size'].apply(lambda x: "100-500m" if 100000000 < x < 500000000 else pass)
df['Classification']=df['Size'].apply(lambda x: "500m-1bi" if 500000000 < x < 1000000000 else pass)
df['Classification']=df['Size'].apply(lambda x: ">1bi" if 1000000000 < x else pass)
Run Code Online (Sandbox Code Playgroud)

可以看出"pass"似乎也不适用于lambda函数:

df['Classification']=df['Size'].apply(lambda x: "<1m" if x<1000000 else pass)
SyntaxError: invalid syntax
Run Code Online (Sandbox Code Playgroud)

关于Pandas中apply方法中lambda函数内多个if语句的正确synthax的任何建议?多线或单线解决方案对我有用.

Vic*_*ria 8

apply lambda 函数实际上在这里完成了工作,我只是想知道问题是什么......因为你的语法看起来不错并且它可以工作......

df1= [80000, 8000000, 8000000000, 800000000000]
df=pd.DataFrame(df1)
df.columns=['size']
df['Classification']=df['size'].apply(lambda x: '<1m' if x<1000000  else '1-10m' if 1000000<x<10000000 else '1bi')
df
Run Code Online (Sandbox Code Playgroud)

输出:

桌子


Ant*_*vBR 6

这是一个可以建立的小示例:

基本上,lambda x: x..是功能的短线。应用真正需要的是一个可以轻松地重新创建自己的功能。

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)
Run Code Online (Sandbox Code Playgroud)

返回值:

        Size Classification
0      80000            <1m
1    8000000          1-10m
2  800000000            N/A
Run Code Online (Sandbox Code Playgroud)


Max*_*axU 5

你可以使用pd.cut功能:

bins = [0, 1000000, 10000000, 50000000, ...]
labels = ['<1m','1-10m','10-50m', ...]

df['Classification'] = pd.cut(df['Size'], bins=bins, labels=labels)
Run Code Online (Sandbox Code Playgroud)