I am trying to populate a new column within a pandas dataframe by using values from several columns. The original columns are either 0
or '1' with exactly a single 1
per series. The new column would correspond to df['A','B','C','D'] by populating new_col = [1, 3, 7, 10]
as shown below. (A 1
at A
means new_col = 1
; if B=1
,new_col = 3
, etc.)
df
A B C D
1 1 0 0 0
2 0 0 1 0
3 0 0 0 1
4 0 1 0 0
The new df
should look like this.
df
A B C D new_col
1 1 0 0 0 1
2 0 0 1 0 7
3 0 0 0 1 10
4 0 1 0 0 3
I've tried to use map
, loc
, and where
but can't seem to formulate an efficient way to get it done. Problem seems very close to this. A couple other posts I've looked at 1 2 3. None of these show how to use multiple columns conditionally to fill a new column based on a list.