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

Joh*_*etz 7 python categories pandas

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

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

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

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

    x    y    z    x_cat    y_cat    z_cat
0   2   -7  -30  success  warning   danger
1   1   -5  -20  success  warning   danger
Run Code Online (Sandbox Code Playgroud)

我尝试过使用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')
Run Code Online (Sandbox Code Playgroud)

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

piR*_*red 14

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

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