2

Suppose i have a DataFrame objects like this:

age_diff    result
       1         0
      -1         1
       0         1

I want to replace negative values in column age_diff by applying to them abs function. Also, if value in age_diff is changed, value in column result should be switched(if it was 0 then to 1, else to 0).

After this transformation DataFrame, shown above, should look like:

age_diff    result
       1         0
       1         0
       0         1

Can, anyone, point me to how can i achieve this?

4 Answers 4

5

Use abs + mask + map by dict:

print (df)
   age_diff  result
0         1       0
1        -1       0
2        -1       1
3         0       1


mask = df['age_diff'] < 0
df['age_diff'] = df['age_diff'].abs()
df['result'] = df['result'].mask(mask, df['result'].map({0:1, 1:0}))
print (df)
   age_diff  result
0         1       0
1         1       1
2         1       0
3         0       1

Another solution - instead map cast to bool and invert by ~:

mask = df['age_diff'] < 0
df['age_diff'] = df['age_diff'].abs()
df['result'] = df['result'].mask(mask, ~(df['result'].astype(bool)))
print (df)
   age_diff  result
0         1       0
1         1       1
2         1       0
3         0       1
Sign up to request clarification or add additional context in comments.

1 Comment

Super, glad can help. Nice day!
2

Another approach you can take is applying a function:

def magic(row):
    if abs(row['age_diff']) != row['age_diff']:
        row['age_diff'] = abs(row['age_diff'])
        row['result'] = 1 - row['result']
    return row

df = df.apply(magic,axis=1)

Comments

1

I get the signs of age_diff with np.sign and manipulate from there.

s = np.sign(df.age_diff.values)

df.age_diff *= s
df.result -= (s == -1)

print(df)

   age_diff  result
0         1       0
1         1       0
2         0       1

Comments

1

Another one liner solution using lambda to get abs of age_diff and then change sign of result if age_diff is negative.

df.apply(lambda x: [abs(x.age_diff),abs((x.age_diff<0) - x.result)],axis=1)
Out[165]: 
   age_diff  result
0         1       0
1         1       0
2         0       1

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.