2

I want to insert values for col 3 as follows:

A+ if col 1 is a and col 2 is positive
A- if col 1 is a and col 2 is negative
B+ if col 1 is B and col 2 is positive
B- if col 1 is B and col 2 is negative

Data:

    COL1  COL2  COL3
0     a    -2
1     a     4
2     b     10
3     b     -8
4     a     10
5     b     5

Therefore I want a resulting df of:

     COL1  COL2  COL3
0     a    -2      A-
1     a     4      A+
2     b     10     B+
3     b     -8     B-
4     a     10     A+
5     b     5      B+
Quang Hoang
  • 146,074
  • 10
  • 56
  • 74
machinelearner07
  • 113
  • 1
  • 1
  • 12

2 Answers2

3

Almost a dup for np.where as noticed by anky_91:

df['COL3'] = df.COL1.str.upper() + np.where(df.COL2.gt(0),'+', '-')

gives the expected output:

  COL1  COL2 COL3
0    a    -2   A-
1    a     4   A+
2    b    10   B+
3    b    -8   B-
4    a    10   A+
5    b     5   B+
Quang Hoang
  • 146,074
  • 10
  • 56
  • 74
0

This captures the off chance that a 0 means no sign symbol

df.COL1.str.upper() + np.sign(df.COL2).map(['', '+', '-'].__getitem__)

0    A-
1    A+
2    B+
3    B-
4    A+
5    B+
dtype: object
piRSquared
  • 285,575
  • 57
  • 475
  • 624