【问题标题】:how to use pandas.assign with lambda and if condition如何将 pandas.assign 与 lambda 和 if 条件一起使用
【发布时间】:2019-10-16 21:49:48
【问题描述】:

谁能告诉我上面的行代码有什么问题

out_inf=q25-1.5*iqr
out_sup=q75+1.5*iqr

df=df.assign(label=1 if ((df'std']<out_inf) is True) | ((df['std']>out_sup) is True) else 0)

我的新专栏只有 0,这是不正确的 通常我必须同时拥有它们,因为我已经用一个简单的 for{ if else } 进行了尝试,但是执行时间太长了。

【问题讨论】:

    标签: python-3.x pandas function assign


    【解决方案1】:

    尝试更好的方法:

    df['label']=((df['std']<out_inf)|(df['std']>out_sup)).astype(int)
    

    或者对于任何其他 if,else 条件使用np.where()

    m=(df['std']<out_inf)|(df['std']>out_sup)
    df['label']=np.where(m,1,0)
    

    (df['std']&lt;out_inf) 之类的条件已经返回布尔输出,因此我们避免进行任何进一步的比较。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-04
      • 1970-01-01
      • 1970-01-01
      • 2015-02-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多