1

I want to set the value of a column(Z) in a pandas dataframe based on the values in other columns (X,Y):

Here is a sample code for that:

for i, row in df.iterrows():
    #print(i, row['Z'])
    if row['X'] == 1 and row['Y'] == 0:
        row['Z'] = 1
    if row['X'] == 0 and row['Y'] == 1:
        row['Z'] = 0
    if row['X'] == 0 and row['Y'] == 0:
        row['Z'] = 2
    if row['X'] == 1 and row['Y'] == 1:
        row['Z'] = 3

what is the way to do so?

2 Answers 2

1

Use numpy.select with & for bitwise AND:

m1 = df['X'] == 0
m2 = df['X'] == 1
m3 = df['Y'] == 0
m4 = df['Y'] == 1

df['Z'] = np.select([m2 & m3, m1 & m4, m1 & m3, m2 & m4], [1,0,2,3])
Sign up to request clarification or add additional context in comments.

Comments

0

if you just want to code the Z value, you could do about

df['Z'] = df['X'] + 2 * df['Y']

if that's not the case, you use pandas.Series.map afterwards :

df['Z'] = df['Z'].map({1:0, 2:1, 0:2, 3:3})

Comments

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.