idt_tt
idt_tt

Reputation: 601

Compute new column in pandas using conditional on other columns

I have a dataframe which looks like this

pd.DataFrame({'A': [5, 2, -3, -2, 1],
   ...:                    'B': [9, -1, 7, -4, 3],
   ...:                    'C': [-5, 2, -6, -8, 9]})
Out[21]: 
   A  B  C
0  5  9 -5
1  2 -1  2
2 -3  7 -6
3 -2 -4 -8
4  1  3  9

For each column value > 0 I want to add 1 and for each column value < 0 I want to subtract 1 before summing up all columns.

resulting dataframe should look like this

   A  B  C   D   Logic
0  5  9 -5  10   (5+1)+(9+1)+(-5-1)
1  2 -1  2   4   (2+1)+(-1-1)+(2+1)
2 -3  7 -6  -3
3 -2 -4 -8 -17
4  1  3  9  16

what is the easiest/quickest way to achieve this?

Upvotes: 0

Views: 45

Answers (2)

Mark Wang
Mark Wang

Reputation: 2757

Numpy has a method called numpy.sign which converts positive number to 1 and negative to -1.

df['D'] = df.add(np.sign(df)).sum(axis=1)

Upvotes: 0

YOLO
YOLO

Reputation: 21719

You can do:

df['D'] = df.add(np.where(df>0, 1, -1)).sum(axis=1)

print(df)

   A  B  C   D
0  5  9 -5  10
1  2 -1  2   4
2 -3  7 -6  -3
3 -2 -4 -8 -17
4  1  3  9  16

Explanation

Create an array of 1 & -1 which can be added to the dataframe using add:

>>> np.where(df>0, 1, -1)

array([[ 1,  1, -1],
       [ 1, -1,  1],
       [-1,  1, -1],
       [-1, -1, -1],
       [ 1,  1,  1]])

Upvotes: 2

Related Questions