2

I have a DataFrame as we can see in Table A with two columns. The values on column A are int starting on 1. The values in column B are binary.

I need to create column C (Table B) in which: if the values on column B are 1, then get the values on column A for that respective row, else if the value on columns B is 0 then column C will be 0 for that respective row.

Example Table A:

+---+---+
| A | B |
+---+---+
| 6 |  1|
| 10|  0|
| 50|  0|
|100|  1|
| 5 |  1|
| 2 |  0|
+---+---+

Table B:

+---+---+---+
| A | B | C |
+---+---+---+
| 6 |  1| 6 |
| 10|  0| 0 |
| 50|  0| 0 |
|100|  1|100|
| 5 |  1| 5 |
| 2 |  0| 0 |
+---+---+---|

code:

# create df
import pandas as pd
d = {'A': [6,10,50,100,5,2], 'B': [1,0,0,1,1,0]}
dfA = pd.DataFrame(data=d) 
dfA

Could anyone help me, please? Thanks! :)

Thaise
  • 1,043
  • 3
  • 16
  • 28

4 Answers4

1

Thanks for the nice minimal working example!

I would solve it like this:

dfA['C'] = dfA['A']          # copy A to C
dfA['C'][dfA['B'] == 0] = 0  # set all positions in C where B is 0 to 0

The resulting dfA:

     A  B    C
0    6  1    6
1   10  0    0
2   50  0    0
3  100  1  100
4    5  1    5
5    2  0    0
Gwang-Jin Kim
  • 9,303
  • 17
  • 30
1

In a numpy where clause the first argument is the condition the next one is the "then" section then the "else" is list

import numpy as np
df['C'] = np.where(df['B']==1, df['B'], 0)    
Back2Basics
  • 7,406
  • 2
  • 32
  • 45
1

If column B is 0 or 1 you can just multiple column A and B using prod on axis=1

dfA['C'] = dfA.prod(axis=1)
#dfA['C'] = dfA[['A','B']].prod(axis=1) if you have more columns
print(dfA)

     A  B    C
0    6  1    6
1   10  0    0
2   50  0    0
3  100  1  100
4    5  1    5
5    2  0    0
anky
  • 74,114
  • 11
  • 41
  • 70
0
dfA['C']=0
dfA.loc[dfA['B']==1, 'C'] = dfA['A']
dfA
Thaise
  • 1,043
  • 3
  • 16
  • 28
  • 1
    While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value – byaruhaf Jan 25 '20 at 15:42