【问题标题】:How to apply function to two columns of Pandas dataframe and two if fucntion如何将函数应用于两列 Pandas 数据框和两列 if 函数
【发布时间】:2021-02-03 14:13:46
【问题描述】:

我想创建一个基于收缩压和舒张压的类。 我有df,其中有SystolicDiastolic 的列。我定义了一个函数:

f = lambda x, y : my_function_expression.

现在我想将 f 应用到 df 的两列 SystolicDiastolic 以在新列 Blood_Pressure 上创建一个类,有点像:

df['Blood_Pressure'] = df['Systolic', 'Diastolic'].apply(lambda x, y : 0 if x >=90 and x <=120 and y >=60 and y <=80 else 1)

怎么办? 还有其他方法吗?

我想要的结果示例:

【问题讨论】:

    标签: python pandas dataframe data-mining


    【解决方案1】:

    一般来说,在使用数据框时,您应该避免使用apply,并尝试根据特征(列)来考虑您的数据。 Pandas 确实提供了许多矢量化操作,而 apply 没有。

    在你的情况下,你可以做between:

    df['Class'] = (df['Systolic'].between(90,120) & 
                   df['Distolic'].between(60,80)
                  ).astype(int)
    

    【讨论】:

    • 反转预期结果 (~df['Systolic'].between(90,120) & ~df['Distolic'].between(60,80) ).astype(int)
    猜你喜欢
    • 2012-10-31
    • 1970-01-01
    • 1970-01-01
    • 2016-09-13
    • 1970-01-01
    • 2021-06-03
    相关资源
    最近更新 更多