1

I have following dataframe

A B C D E
-0.1 0 0.2 0 4
0 0 -1 -2 5

I would like an output as following based on A,B belong to category X and C,D,E belong to category Y -

A B C D E
-cat X 0 +cat Y 0 +cat Y
0 0 -cat Y -cat Y +cat Y

It basically checks the column name and assigns a category and checks the value to assign a sign. Is there any easy way to do this in Python? I am using COLAB, so probably have latest version.

1 Answer 1

1

One way could be to just choose whatever columns you want and then perform check like below:

import numpy as np

for col in ['A','B']:
    df[col] = [x if x == 0 else '-Cat X' if x < 0 else '+ Cat X' for x in df[col]]

for col in ['C','D','E']:
    df[col] = [x if x == 0 else '-Cat Y' if x < 0 else '+ Cat Y' for x in df[col]]

This should produce the required result.

Sign up to request clarification or add additional context in comments.

2 Comments

If there are many categories and many columns this would look very ugly, is there a way I can reference a dictionary and use X/Y as value of some variable(object)?
I suggest np.select then. It allows you to set multiple conditions and their choices along with default values if required.numpy.org/doc/stable/reference/generated/numpy.select.html

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.