I have a pandas dataframe and I want to create a new column BB based on the below condition.
- Create a new column BB, if the values in column TGR1 is 0, assign 0 to BB else,
- The value in TGR1 is not 0, look up the columns ('1','2','3') that corresponds with the value in TGR1 assign the value in that column(either '1','2','3') to the new column BB.
I was able to achieve the first step using
df.loc[df['TGR1'] == 0, 'BB'] = 0
I also tried to use np.where to come up with but I can figure out the right way to go about this.
df['BB'] = np.where(df.TGR1 == 0,0, df.columns == test.TGR1.value )
Dist Track EVENT_ID Date 1 2 3 TGR1 TGR2
311m Cran 174331755 2020-10-19 34.00 5.18 19.10 1 0
311m Cran 174331755 2020-10-19 34.00 5.18 19.10 2 1
311m Cran 174331755 2020-10-19 34.00 5.18 19.10 0 2
311m Cran 174331755 2020-10-19 34.00 5.18 19.10 3 1
311m Cran 174331755 2020-10-19 34.00 5.18 19.10 2 2
311m Cran 174331755 2020-10-19 34.00 5.18 19.10 1 2
Expected Output:
Dist Track EVENT_ID Date 1 2 3 TGR1 TGR2 BB
311m Cran 174331755 2020-10-19 34.00 5.18 19.10 1 0 34.00
311m Cran 174331755 2020-10-19 34.00 5.18 19.10 2 1 5.18
311m Cran 174331755 2020-10-19 34.00 5.18 19.10 0 2 0
311m Cran 174331755 2020-10-19 34.00 5.18 19.10 3 1 19.10