0
ColG Col2 Col3 Len    Sign
G1   1    30   300    +
G2   20   80   200    +
G3   455  720  1000   -
G4   3    40   100    -
G4   2    90   130    +

and here is the idea, for each row, if the Sign is -, then do :

Len-Col2 > NewCol3
Len-Col3 > NewCol2

exemple

1000-720=280
1000-455=545
100-40=60
100-3=97

and get :

ColG Col2 Col3 Len    Sign NewCol2  NewCol3
G1   1    30   300    +    1        30
G2   20   80   200    +    20       80
G3   455  720  1000   -    280      545
G4   3    40   100    -    60       97
G4   2    90   130    +    2        90

Thank you for your help

2
  • It seems expected output has swapped col2, col3 Commented Apr 28, 2020 at 11:00
  • 1
    Oops yes I rectified, it is Len-Col2 that gives NewCol3 Commented Apr 28, 2020 at 11:47

2 Answers 2

2

You need processing each column separately, e.g. compare by Series.eq with numpy.where:

m = df['Sign'].eq('-')

df['NewCol2'] = np.where(m, df['Len'].sub(df['Col3']), df['Col2'])
df['NewCol3'] = np.where(m, df['Len'].sub(df['Col2']), df['Col3'])

Or with Series.mask:

df['NewCol2'] = df['Col2'].mask(m, df['Len'].sub(df['Col3']))
df['NewCol3'] = df['Col3'].mask(m, df['Len'].sub(df['Col2']))

print (df)
  ColG  Col2  Col3   Len Sign  NewCol2  NewCol3
0   G1     1    30   300    +        1       30
1   G2    20    80   200    +       20       80
2   G3   455   720  1000    -      280      545
3   G4     3    40   100    -       60       97
4   G4     2    90   130    +        2       90
Sign up to request clarification or add additional context in comments.

Comments

1

If your dataframe is not too big, you can try this.

def new_col2(row):
  if row['Sign'] == '-':
    return row['Len'] - row['Çol2']
  return row['Col2']

def new_col3(row):
  if row['Sign'] == '-':
    return row['Len'] - row['Çol3']
  return row['Col3']

df['NewCol2'] = df.apply(new_col2, axis=1)
df['NewCol3'] = df.apply(new_col3, axis=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.