在pandas数据帧中对列的表达式进行条件评估

时间:2017-08-21 09:49:51

标签: python pandas dataframe conditional

我有以下数据框: enter image description here

我正在尝试根据以下规则根据CHART_TYPE列值根据以下条件计算sigma:

If chart type is X-BAR -> SIGMA = (UPPER_CONTROL_LIMIT - LOW_CONTROL_LIMIT)/6
If chart type is MIN -> SIGMA = (TARGET - LOW_CONTROL_LIMIT)/3
If chart type is MAX -> SIGMA = (UPPER_CONTROL_LIMIT - TARGET)/3

请告知

1 个答案:

答案 0 :(得分:1)

您应该可以在这里使用df.apply

首先,创建一个帮手:

def func(row):
    if row['CHART_TYPE'] == 'X_BAR':
        return (row['UPPER_CONTROL_LIMIT'] - row['LOW_CONTROL_LIMIT']) / 6

    elif row['CHART_TYPE'] == 'MIN':
        return (row['TARGET'] - row['LOW_CONTROL_LIMIT']) / 3

    return (row['UPPER_CONTROL_LIMIT'] - row['TARGET']) / 3

现在,请致电df.apply

df.SIGMA = df.apply(func, axis=1)