熊猫:根据价值落在范围内的位置分配类别

时间:2017-06-20 16:59:10

标签: python pandas categories

我有以下范围和一个pandas DataFrame:

x >= 0        # success
-10 <= x < 0  # warning
X < -10       # danger

df = pd.DataFrame({'x': [2, 1], 'y': [-7, -5], 'z': [-30, -20]})

我想根据数据框落在定义范围内的值对数据框中的值进行分类。所以我希望最终的DF看起来像这样:

    x    y    z    x_cat    y_cat    z_cat
0   2   -7  -30  success  warning   danger
1   1   -5  -20  success  warning   danger

我已尝试使用category数据类型,但它似乎无法在任何地方定义范围。

for category_column, value_column in zip(['x_cat', 'y_cat', 'z_cat'], ['x', 'y', 'z']):
    df[category_column] = df[value_column].astype('category')

我可以使用category数据类型吗?如果没有,我可以在这做什么?

5 个答案:

答案 0 :(得分:12)

pandas.cut

c = pd.cut(
    df.stack(),
    [-np.inf, -10, 0, np.inf],
    labels=['danger', 'warning', 'success']
)
df.join(c.unstack().add_suffix('_cat'))

   x  y   z    x_cat    y_cat   z_cat
0  2 -7 -30  success  warning  danger
1  1 -5 -20  success  warning  danger

numpy

v = df.values
cats = np.array(['danger', 'warning', 'success'])
code = np.searchsorted([-10, 0], v.ravel()).reshape(v.shape)
cdf = pd.DataFrame(cats[code], df.index, df.columns)
df.join(cdf.add_suffix('_cat'))

   x  y   z    x_cat    y_cat   z_cat
0  2 -7 -30  success  warning  danger
1  1 -5 -20  success  warning  danger

答案 1 :(得分:3)

您可以使用assign来创建新列。对于每个新列,使用apply来过滤该系列。

public EventHandler TextBoxClick;
public EventHandler ButtonClick;

// Attach this handler to your TextBox.Click event
private void TextBox_Click(object sender, EventArgs e)
{
    if (TextBoxClick != null)
        TextBoxClick(sender, e);
}

// Attach this handler to your Button.Click event
private void Button_Click(object sender, EventArgs e)
{
    if (ButtonClick != null)
        ButtonClick(sender, e);
}

将导致

public

答案 2 :(得分:2)

您可以编写一个小函数,然后使用apply:

将每个系列传递给函数
df = pd.DataFrame({'x': [2, 1], 'y': [-7, -5], 'z': [-30, -20]})

def cat(x):
    if x <-10:
        return "Danger"
    if x < 0:
        return "Warning"
    return "Success"

for col in df.columns:
    df[col] = df[col].apply(lambda x: cat(x))

答案 3 :(得分:1)

你可以使用pandas this answer,但你需要逐列应用它(因为该函数在1-d输入上运行):

labels = df.apply(lambda x: pd.cut(x, [-np.inf, -10, 0, np.inf], labels = ['danger', 'warning', 'success']))

          x        y       z
0  success  warning  danger
1  success  warning  danger

所以你可以这样做:

pd.concat([df, labels.add_prefix('_cat')], axis = 1)

   x  y   z     cat_x     cat_y    cat_z
0  2 -7 -30  success  warning  danger
1  1 -5 -20  success  warning  danger

答案 4 :(得分:0)

这是针对此类事情的三元方法。

filter_method = lambda x: 'success' if x >= 0 else 'warning' if (x < 0 and x >= -10) else 'danger' if x < -10 else None
df[category_column] = df[value_column].apply(filter_method)